#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#ifdef WIN32
#include <WinSock2.h>
#include <ws2tcpip.h>
#pragma comment(lib,"Ws2_32.lib")
//end WIN32
#else //Linux
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif //end Linux
typedef std::vector<struct in_addr> array_in_addr;
int GetHostsByName( const char *host_name,array_in_addr* pArrayaddr)
{
int n=0;
struct addrinfo hints,*res;
struct addrinfo* p_addrinfo = NULL;
memset( &hints,0,sizeof(struct addrinfo) );
hints.ai_flags = AI_CANONNAME; //客户端一般就用这个 AI_CANONNAME,服务端建议用:AI_PASSIVE
hints.ai_family = AF_INET; //AF_INET:IPv4 ,AF_INET6:IPv6
hints.ai_socktype = SOCK_STREAM; //IPPROTO_IP 可能会产生多个重复IP
sockaddr_in* p_sockaddr_in;
if( (n = getaddrinfo( host_name,NULL, &hints, &res) ) != 0)
return 0;
printf("domain:%s \r\n",host_name);
p_addrinfo = res;
while(p_addrinfo!=NULL)
{
pArrayaddr->push_back( ((sockaddr_in*)p_addrinfo->ai_addr)->sin_addr);
printf("ip%d: %s \r\n",pArrayaddr->size(),inet_ntoa(((sockaddr_in*)p_addrinfo->ai_addr)->sin_addr));
p_addrinfo = p_addrinfo->ai_next;
}
freeaddrinfo(res);
return pArrayaddr->size();
}
int main(int argc, char *argv[])
{
int nRet;
const char* pszHost = NULL;
array_in_addr inaddrs;
if (argc != 2) {
printf("Usage:%s <hostname> \r\n",argv[0]);
return -1;
}
pszHost = argv[1];
#ifdef WIN32
WSADATA wsaData;
int err = WSAStartup( 0x0202, &wsaData );
if ( err != 0 ) {
printf("socket init(WSAStartup) failure \r\n");
return 1;
}
#endif
GetHostsByName(pszHost,&inaddrs);
#ifdef WIN32
WSACleanup();
#endif
return 0;
}
参见网址:
http://baike.baidu.com/view/6757218.htm