connection.c
changeset 153 b223089872b6
parent 131 b5ad49852adc
child 163 780bf4f348f3
--- a/connection.c
+++ b/connection.c
@@ -16,36 +16,38 @@
 #include <sys/types.h>
 #include <sys/socket.h>
 
-int connection (char *ip, unsigned short port)
+int connection (char *server, char *port)
 {
-    struct hostent *hs;
-    struct sockaddr_in sock;
+    struct addrinfo hints;
+    struct addrinfo *result, *rp;
 
-    int sockfd;
-
-    memset (&sock, 0, sizeof (sock));
-    sock.sin_family = PF_INET;
-    sock.sin_port = htons (port);
+    int sockfd = -1;
 
-    if ((sock.sin_addr.s_addr = inet_addr (ip)) == -1) {
-        if ((hs = gethostbyname (ip)) == NULL) {
-            perror ("[-] Error");
-            return -1;
-        }
-        sock.sin_family = hs->h_addrtype;
-        memcpy (&sock.sin_addr.s_addr, hs->h_addr_list[0], hs->h_length);
-    }
+    memset (&hints, 0, sizeof (struct addrinfo));
+    hints.ai_family = AF_UNSPEC;
+    hints.ai_socktype = SOCK_STREAM;
+    hints.ai_flags = 0;
+    hints.ai_protocol = IPPROTO_TCP;
 
-    if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) < 0) {
-        perror ("[-] Error");
+    if (getaddrinfo (server, port, &hints, &result) != 0) {
+        perror ("getaddrinfo");
         return -1;
     }
 
-    if (connect (sockfd, (struct sockaddr *)&sock, sizeof (sock)) < 0) {
-        perror ("[-] Error ");
-        return -1;
+    for (rp = result; rp != NULL; rp = rp->ai_next) {
+        if ((sockfd = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1)
+            continue;
+
+        if (connect (sockfd, rp->ai_addr, rp->ai_addrlen) != -1) {
+            break;
+        }
+        close (sockfd);
+        sockfd = -1;
     }
 
+    if (result != NULL)
+        freeaddrinfo (result);
+
     return (sockfd);
 }
 
@@ -58,16 +60,16 @@
     int num;
 
     if (argc != 3) {
-        printf ("Usage: %s <ipaddr> <port>\n", argv[0]);
+        printf ("Usage: %s <ipaddr> <service>\n", argv[0]);
         return EXIT_FAILURE;
     }
 
-    if ((sockfd = connection (argv[1], atoi (argv[2]))) < 0) {
-        printf ("Connection error: %s:%d\n", argv[1], atoi (argv[2]));
+    if ((sockfd = connection (argv[1], argv[2])) < 0) {
+        printf ("Connection error: %s:%s\n", argv[1], argv[2]);
         return EXIT_FAILURE;
     }
 
-    if (write (sockfd, "GET /\r\n", 7) == -1) {
+    if (write (sockfd, "GET / HTTP/1.0\r\n\r\n", 18) == -1) {
         perror ("write");
         return EXIT_FAILURE;
     }