wrong original functions names typo fixed
[overhosts.git] / test.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <string.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netdb.h>
9 #include <arpa/inet.h>
10
11 #define BUF_SIZE 500
12
13 int
14 main(int argc, char *argv[])
15 {
16     struct addrinfo hints;
17     struct addrinfo *result, *rp;
18     int s;
19
20     if (argc < 3) {
21         fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
22         exit(EXIT_FAILURE);
23     }
24
25     /* Obtain address(es) matching host/port */
26
27     memset(&hints, 0, sizeof(struct addrinfo));
28     hints.ai_family = 0;    /* Allow IPv4 or IPv6 */
29     hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
30     /* hints.ai_flags = 0; */
31     hints.ai_flags = AI_CANONNAME;    /* For wildcard IP address */
32     hints.ai_protocol = 0;          /* Any protocol */
33     hints.ai_canonname = NULL;
34     hints.ai_addr = NULL;
35     hints.ai_next = NULL;
36
37     s = getaddrinfo(argv[1], argv[2], &hints, &result);
38     if (s != 0) {
39         fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
40         exit(EXIT_FAILURE);
41     }
42
43     /* getaddrinfo() returns a list of address structures.
44        Try each address until we successfully connect(2).
45        If socket(2) (or connect(2)) fails, we (close the socket
46        and) try the next address. */
47
48     for (rp = result; rp != NULL; rp = rp->ai_next) {
49         printf("ai_flags:    %d\n", rp->ai_flags);
50         printf("ai_family:   %d\n", rp->ai_family);
51         printf("ai_socktype: %d\n", rp->ai_socktype);
52         printf("ai_protocol: %d\n", rp->ai_protocol);
53         printf("ai_addrlen:  %d\n", rp->ai_addrlen);
54         printf("ai_addr.type: %d\n", rp->ai_addr->sa_family); /* PF_INET */
55         if (rp->ai_addr->sa_family == AF_INET) {
56             printf("sin_port: %d\n" , ntohs(((struct sockaddr_in *)rp->ai_addr)->sin_port));
57             printf("sin_addr: %s\n", inet_ntoa(((struct sockaddr_in *)rp->ai_addr)->sin_addr));
58         }
59         printf("ai_canonname:[%s]\n", rp->ai_canonname);
60     }
61
62     freeaddrinfo(result);           /* No longer needed */
63
64     exit(EXIT_SUCCESS);
65 }