使用gethostname()函数和gethostbyname()函数获取主机相关信息
gethostname():返回本地主機的標準主機名
原型如下:
#include <unistd.h> int gethostname(char *name, size_t len); 參數說明: 這個函數需要兩個參數:接收緩沖區name,其長度必須為len字節或是更長,存獲得的主機名。接收緩沖區name的最大長度: 返回值:如果函數成功,則返回0。如果發生錯誤則返回-1.錯誤號存放在外部變量errno中。gethostbyname()函數說明----用域名或主機名獲取IP地址
包含頭文件 #include <netdb.h> #include <sys/socket.h>函數原型: struct hostent *gethostbyname(const char *name); 這個函數的傳入值是域名或者主機名,例如"www.google.cn"等等。傳出值,是一個hostent的結構。如果函數調用失敗,將返回NULL。 返回hostent結構體類型指針: struct hostent {char *h_name; /* official name of host */char **h_aliases; /*alias list */int h_addrtype; /* host address type */int h_length; /* length of address */char **h_addr_list; /* list of addresses*/ } #define h_addr h_addr_list[0] /* for backward compatibility */?hostent->h_name
? ?表示的是主機的規范名。例如www.google.com的規范名其實是www.l.google.com.
?hostent->h_aliases
? ? 表示的是主機的別名www.google.com就是google他自己的別名。有的時候,有的主機可能有好幾個別名,這些,其實都是為了易于用戶記憶而為自己的網站多取的名字。
? hostent->h_addrtype
? ? 表示的是主機ip地址的類型,到底是ipv4(AF_INET),還是ipv6(AF_INET6)
? hostent->h_length
? ? 表示的是主機ip地址的長度
? hostent->h_addr_list
? ? 表示的是主機的ip地址,注意,這個是網絡字節存儲的。千萬不要直接用printf帶%s參數來打這個東西,會有問題的哇。所以到真正需要打印出這個IP的話,需要調用inet_ntop()。
? const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
? ? 這個函數,是將類型為af的網絡地址結構src,轉換為主機序的字符串形式,存放在長度為cnt的字符串中。返回指向dst的一個指針。如果函數調用錯誤,返回值是NULL。
? 示例如下:
#include <stdio.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h>void handler(int sig) {printf("recv a sig = %d\n", sig);exit(EXIT_SUCCESS); }#define ERR_EXIT(m) \do { \perror(m); \exit(EXIT_FAILURE); \} while(0);int main(void) {char host[100] = {0};if (gethostname(host, sizeof(host)) < 0) {ERR_EXIT("gethostname");}struct hostent *hp;if ((hp = gethostbyname(host)) == NULL) {ERR_EXIT("gethostbyname");}int i = 0;while (hp->h_addr_list[i] != NULL) {printf("hostname: %s\n", hp->h_name);printf(" ip:%s\n", inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));i++;}return 0; }? ? 編譯運行
? -------------------------
# gcc -o getinfo getinfo.c #./getinfohostname:www.server1.comip:69.172.201.208? 注意:試驗時主機名要是域名格式(如www.server1.com,若函數為server1時gethostbyname函數返回為NULL),gethostbyname()函數才能獲取到信息,否則返回NULL。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的使用gethostname()函数和gethostbyname()函数获取主机相关信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: getsockname和getpeern
- 下一篇: 《深入理解Nginx 模块开发与架构解析