TCP/IP socket programming in C(二)

来源:互联网 发布:tcp端口是什么 编辑:程序博客网 时间:2024/05/16 12:51
// 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/

0 0
原创粉丝点击