通过函数getaddrinfo()函数将域名转换为对应的IP
struct addrinfo
{
int ai_flags; /* Input flags. */
int ai_family; /* Protocol family for socket. */
int ai_socktype; /* Socket type. */
int ai_protocol; /* Protocol for socket. */
socklen_t ai_addrlen; /* Length of socket address. */
struct sockaddr *ai_addr; /* Socket address for socket. */
char *ai_canonname; /* Canonical name for service location. */
struct addrinfo *ai_next; /* Pointer to next in list. */
};
————————————————
版权声明:本文为CSDN博主「Stoneshen1211」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011003120/article/details/78277133
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
int main(int argc,char **argv)
{
int ret = -1;
struct addrinfo *res;
struct addrinfo hint;
struct addrinfo *curr;
char ipstr[16];
if(argc != 2)
{
printf("parameter error\n");
return -1;
}
bzero(&hint,sizeof(hint));
hint.ai_family = AF_INET;
hint.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(argv[1],NULL,&hint,*res);
if(ret != 0)
{
printf("getaddrinfo error\n");
return -1;
}
for(curr = res;curr != NULL;curr = curr->ai_next)
{
inet_ntop(AF_INET,&(((struct sockaddr*)(curr->ai_addr))->sin_addr),ipstr,16);
}
freeaddrinfo(res);
return 0;
}
$ ./test www.baidu.com
14.215.177.38
14.215.177.39