您的位置:首页 > 理论基础 > 计算机网络

TCP/IP socket programming in C(二)

2014-01-20 22:09 274 查看
// get_ipaddr.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/socket.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
char *hostname = "www.baidu.com";
char ip[100];
struct hostent *he;
struct in_addr **addr_list;
int i;

if ((he = gethostbyname(hostname)) == NULL) {
// gethostbyname failed
herror("gethostbyname");
return 1;
}

// Cast the h_addr_list to in_addr, since h_addr_list also has the
// ip address in long format only
addr_list = (struct in_addr **)he->h_addr_list;

for (i = 0; addr_list[i] != NULL; i++) {
// Return the first one
strcpy(ip, inet_ntoa(*addr_list[i]));
}

printf("%s resolved to : %s\n", hostname, ip);
return 0;
}


原文:http://www.binarytides.com/socket-programming-c-linux-tutorial/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: