|
通过如“www.163.com”获取ip地址。
#include "global.h"
/*
* @brief 通过主机名host如"www.163.com"获得ip地址
* @param[in] host 主机名
* @param[out] ip 缓冲区,兼容ipv4和v6
* @return 成功返回0,失败返回负值。
*/
int getipbyhost(char *host, unsigned char ip[INET6_ADDRSTRLEN])
{
struct hostent *h;
char *ptr, **pptr;
int i;
if (host == NULL || ip == NULL)
return -1;
h = gethostbyname(host);
if (h == NULL)
return -2;
switch(h->h_addrtype)
{
case AF_INET:
case AF_INET6:
//#define h_addr h_addr_list[0] 在netdb.h中
ptr = inet_ntop(h->h_addrtype, h->h_addr, ip, INET6_ADDRSTRLEN);
printf("ip = %s \n", ip);
}
printf("Official Hostname: %s \n", h->h_name); //官方名字
for (pptr = h->h_aliases; *pptr != NULL; pptr++) //别名
printf("Alias: %s\n", *pptr);
printf("INET6_ADDRSTRLEN: %d, INET_ADDRSTRLEN: %d \n",
INET6_ADDRSTRLEN, INET_ADDRSTRLEN);
if (i == 32)
printf("Warnning:Too Much ip for the host."
" Only fetch 32 ahead this time!\n");
return 0;
}
int main(int argc, char **argv)
{
int ret;
unsigned char ip[INET6_ADDRSTRLEN];
if (argc != 2)
printf("Usage: command <arg1>\n");
getipbyhost(argv[1], ip);
return 0;
} |
|
|