14 |
14 |
15 #include <netinet/in.h> |
15 #include <netinet/in.h> |
16 #include <sys/types.h> |
16 #include <sys/types.h> |
17 #include <sys/socket.h> |
17 #include <sys/socket.h> |
18 |
18 |
19 int connection (char *ip, unsigned short port) |
19 int connection (char *server, char *port) |
20 { |
20 { |
21 struct hostent *hs; |
21 struct addrinfo hints; |
22 struct sockaddr_in sock; |
22 struct addrinfo *result, *rp; |
23 |
23 |
24 int sockfd; |
24 int sockfd = -1; |
25 |
25 |
26 memset (&sock, 0, sizeof (sock)); |
26 memset (&hints, 0, sizeof (struct addrinfo)); |
27 sock.sin_family = PF_INET; |
27 hints.ai_family = AF_UNSPEC; |
28 sock.sin_port = htons (port); |
28 hints.ai_socktype = SOCK_STREAM; |
|
29 hints.ai_flags = 0; |
|
30 hints.ai_protocol = IPPROTO_TCP; |
29 |
31 |
30 if ((sock.sin_addr.s_addr = inet_addr (ip)) == -1) { |
32 if (getaddrinfo (server, port, &hints, &result) != 0) { |
31 if ((hs = gethostbyname (ip)) == NULL) { |
33 perror ("getaddrinfo"); |
32 perror ("[-] Error"); |
|
33 return -1; |
|
34 } |
|
35 sock.sin_family = hs->h_addrtype; |
|
36 memcpy (&sock.sin_addr.s_addr, hs->h_addr_list[0], hs->h_length); |
|
37 } |
|
38 |
|
39 if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) < 0) { |
|
40 perror ("[-] Error"); |
|
41 return -1; |
34 return -1; |
42 } |
35 } |
43 |
36 |
44 if (connect (sockfd, (struct sockaddr *)&sock, sizeof (sock)) < 0) { |
37 for (rp = result; rp != NULL; rp = rp->ai_next) { |
45 perror ("[-] Error "); |
38 if ((sockfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1) |
46 return -1; |
39 continue; |
|
40 |
|
41 if (connect (sockfd, rp->ai_addr, rp->ai_addrlen) != -1) { |
|
42 break; |
|
43 } |
|
44 close (sockfd); |
|
45 sockfd = -1; |
47 } |
46 } |
|
47 |
|
48 if (result != NULL) |
|
49 freeaddrinfo (result); |
48 |
50 |
49 return (sockfd); |
51 return (sockfd); |
50 } |
52 } |
51 |
53 |
52 int main (int argc, char **argv) |
54 int main (int argc, char **argv) |
56 int sockfd; |
58 int sockfd; |
57 |
59 |
58 int num; |
60 int num; |
59 |
61 |
60 if (argc != 3) { |
62 if (argc != 3) { |
61 printf ("Usage: %s <ipaddr> <port>\n", argv[0]); |
63 printf ("Usage: %s <ipaddr> <service>\n", argv[0]); |
62 return EXIT_FAILURE; |
64 return EXIT_FAILURE; |
63 } |
65 } |
64 |
66 |
65 if ((sockfd = connection (argv[1], atoi (argv[2]))) < 0) { |
67 if ((sockfd = connection (argv[1], argv[2])) < 0) { |
66 printf ("Connection error: %s:%d\n", argv[1], atoi (argv[2])); |
68 printf ("Connection error: %s:%s\n", argv[1], argv[2]); |
67 return EXIT_FAILURE; |
69 return EXIT_FAILURE; |
68 } |
70 } |
69 |
71 |
70 if (write (sockfd, "GET /\r\n", 7) == -1) { |
72 if (write (sockfd, "GET / HTTP/1.0\r\n\r\n", 18) == -1) { |
71 perror ("write"); |
73 perror ("write"); |
72 return EXIT_FAILURE; |
74 return EXIT_FAILURE; |
73 } |
75 } |
74 |
76 |
75 while ((num = read (sockfd, buffer, 1023)) != 0) { |
77 while ((num = read (sockfd, buffer, 1023)) != 0) { |