struct hostent *gethostbyname(const char *hostname);hostname 为主机名,也就是域名。使用该函数时,只要传递域名字符串,就会返回域名对应的 IP 地址。返回的地址信息会装入 hostent 结构体,该结构体的定义如下:
struct hostent{
char *h_name; //official name
char **h_aliases; //alias list
int h_addrtype; //host address type
int h_length; //address lenght
char **h_addr_list; //address list
}
从该结构体可以看出,不只返回 IP 地址,还会附带其他信息,各位读者只需关注最后一个成员 h_addr_list。下面是对各成员的说明:
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
int main(){
WSADATA wsaData;
WSAStartup( MAKEWORD(2, 2), &wsaData);
struct hostent *host = gethostbyname("www.baidu.com");
if(!host){
puts("Get IP address error!");
system("pause");
exit(0);
}
//别名
for(int i=0; host->h_aliases[i]; i++){
printf("Aliases %d: %s\n", i+1, host->h_aliases[i]);
}
//地址类型
printf("Address type: %s\n", (host->h_addrtype==AF_INET) ? "AF_INET": "AF_INET6");
//IP地址
for(int i=0; host->h_addr_list[i]; i++){
printf("IP addr %d: %s\n", i+1, inet_ntoa( *(struct in_addr*)host->h_addr_list[i] ) );
}
system("pause");
return 0;
}
运行结果:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有