socket编程

思维导图.jpg

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <sys/types.h>                                         
#include <sys/socket.h>                                        
#include <netdb.h>                                             
#include <arpa/inet.h>                                         
#include <stdio.h>                                             
#include <stdlib.h>                                            
#define MAXLINE 1024                                           


int main(int argc, char **argv)                                
{                                                              
    struct addrinfo *p,*listp, hints;                          
    char buf[MAXLINE];                                         
    int rc, flags;                                             

    if(argc != 2){                                             
        fprintf(stderr,"usage: %s <domain niane>\n", argv[0]);
        exit(0);                                               
    }                                                          


    //Get a list of addrinfo records                           
    memset(&hints,0,sizeof(struct addrinfo));                  
    hints.ai_family = AF_INET;                                 
    hints.ai_socktype = SOCK_STREAM;                           
    if((rc=getaddrinfo(argv[1],NULL,&hints,&listp))!=0){       
    //Get a list of addrinfo records                                       
    memset(&hints,0,sizeof(struct addrinfo));                              
    hints.ai_family = AF_INET;                                             
    hints.ai_socktype = SOCK_STREAM;                                       
    if((rc=getaddrinfo(argv[1],NULL,&hints,&listp))!=0){                   
        fprintf(stderr, "getaddrinfo error: %s\n",gai_strerror(rc));       
        exit(1);                                                           
    }                                                                      

    // Walk the list and display each IP address                           
    flags = NI_NUMERICHOST;                                                
    for(p=listp;p;p=p->ai_next){                                           
        getnameinfo(p->ai_addr,p->ai_addrlen, buf, MAXLINE,NULL,0,flags);  
        printf("%s\n",buf);                                                
    }                                                                      
    freeaddrinfo(listp);                                                   
    exit(0);                                                               
}           
1
2
3
4
5
[root@f3c6f9f95723 inet]# ./hostinfo www.baidu.com
14.215.177.38
14.215.177.39
[root@f3c6f9f95723 inet]# ./hostinfo www.ustc.edu.cn
218.22.21.21