- /*************************************************************************
- > File Name: gethostbyname.cpp
- > Author: zhongsx
- > Mail: zhongsx@broadtech.com.cn
- > Created Time: Tue 29 May 2012 10:24:23 PM CST
- ************************************************************************/
- #include <stdio.h>
- #include <netdb.h>
- #include <arpa/inet.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 **pptr;
- 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]
- //char const *haddr = h->h_addr;
- inet_ntop(h->h_addrtype, h->h_addr, reinterpret_cast<char*>(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);
- 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;
- }
- //该片段来自于http://www.codesnippet.cn/detail/240620134223.html
来源: http://www.codesnippet.cn/detail/240620134223.html