|
1 /** |
|
2 * test/demos/connection.c |
|
3 * Copyright (C) 2008 mussolini |
|
4 * Copyright (C) 2008 mbroeker |
|
5 */ |
|
6 |
|
7 #include <stdio.h> |
|
8 #include <stdlib.h> |
|
9 #include <unistd.h> |
|
10 #include <string.h> |
|
11 |
|
12 #include <netdb.h> |
|
13 #include <arpa/inet.h> |
|
14 |
|
15 int connection (char *ip, unsigned short port) |
|
16 { |
|
17 struct hostent *hs; |
|
18 struct sockaddr_in sock; |
|
19 int sockfd; |
|
20 |
|
21 memset (&sock, 0, sizeof (sock)); |
|
22 sock.sin_family = AF_INET; |
|
23 sock.sin_port = htons (port); |
|
24 |
|
25 if ((sock.sin_addr.s_addr = inet_addr (ip)) == -1) { |
|
26 if ((hs = gethostbyname (ip)) == NULL) { |
|
27 perror ("[-] Error"); |
|
28 return -1; |
|
29 } |
|
30 sock.sin_family = hs->h_addrtype; |
|
31 memcpy (&sock.sin_addr.s_addr, hs->h_addr, hs->h_length); |
|
32 } |
|
33 |
|
34 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { |
|
35 perror ("[-] Error"); |
|
36 return -1; |
|
37 } |
|
38 |
|
39 if (connect (sockfd, (struct sockaddr *)&sock, sizeof (sock)) < 0) { |
|
40 perror ("[-] Error "); |
|
41 return -1; |
|
42 } |
|
43 |
|
44 return (sockfd); |
|
45 } |
|
46 |
|
47 int main (int argc, char **argv) |
|
48 { |
|
49 char buffer[1024]; |
|
50 int sockfd; |
|
51 int num; |
|
52 |
|
53 if (argc != 3) { |
|
54 printf ("Usage: %s <ipaddr> <port>\n", argv[0]); |
|
55 return EXIT_SUCCESS; |
|
56 } |
|
57 |
|
58 if ((sockfd = connection (argv[1], atoi (argv[2]))) < 0) { |
|
59 printf ("Connection error: %s:%d\n", argv[1], atoi (argv[2])); |
|
60 return EXIT_FAILURE; |
|
61 } |
|
62 |
|
63 write (sockfd, "GET /\r\n", 7); |
|
64 |
|
65 while ((num = read (sockfd, buffer, 1023)) != 0) { |
|
66 buffer[num] = 0; |
|
67 printf ("%s", buffer); |
|
68 } |
|
69 |
|
70 return close (sockfd); |
|
71 } |