原文
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char** argv)
{
assert(argc == 2);
const char* hostname = argv[1];
struct hostent* host;
host = gethostbyname(hostname);
if (NULL == host)
{
perror("can not get host by hostname");
exit(EXIT_FAILURE);
}
printf("host ip=%s\n", inet_ntoa(*((struct in_addr*)host->h_addr)));
return EXIT_SUCCESS;
}
本人文峰聊书斋在centos6平台验证
[root@www ble_mesh]# ./a.out
host ip=14.215.177.38
[root@www ble_mesh]#
文峰聊书斋另外加入:
#define SOCKADDR_IN(addr, ip, port) do{ \
memset(&(addr), 0, sizeof(addr)); \
(addr).sin_family = AF_INET; \
(addr).sin_addr.s_addr = inet_addr(ip); \
(addr).sin_port = htons(port); \
if ((addr).sin_addr.s_addr == INADDR_NONE){ \
struct hostent* pHost = gethostbyname(ip); \
if (pHost == NULL){return ;} \
memcpy(&(addr).sin_addr, pHost->h_addr_list[0], pHost->h_length);} \
}while(0)
struct sockaddr_in servaddr;
SOCKADDR_IN(servaddr,"", 5000);
//SOCKADDR_IN(servaddr,"192.168.0.11", 5000);
printf("baidu%s\n",inet_ntoa(servaddr.sin_addr));
阅读(1357) | 评论(0) | 转发(0) |