summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--sock.c48
1 files changed, 30 insertions, 18 deletions
diff --git a/sock.c b/sock.c
index f86b41a..778f832 100644
--- a/sock.c
+++ b/sock.c
@@ -6,6 +6,7 @@
#include <string.h>
#include <errno.h>
+#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
@@ -49,33 +50,44 @@ static const char *GetLine(void)
}
-static int Connect(const char *n, int p)
+static int Connect(const char *n, const char *p)
{
- struct hostent *remote;
- struct sockaddr_in addr;
- int sock;
+ struct addrinfo *addr, *addr_p;
+ struct addrinfo hints = {0};
+ int status;
+ int sock = -1;
- if (!(remote=gethostbyname(n)))
- {
- fprintf(stderr,"%s: unknown host %s\n",name,n);
- exit(EXIT_FAILURE);
- }
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
- memcpy(&addr.sin_addr, remote->h_addr, remote->h_length);
+ status = getaddrinfo(n, p, &hints, &addr);
- if ((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
+ if (status)
{
- perror(name);
+ fprintf(stderr, "%s: %s\n", name, gai_strerror(status));
exit(EXIT_FAILURE);
}
- addr.sin_family=AF_INET;
- addr.sin_port=htons(p);
+ for(addr_p = addr; addr_p && sock == -1; addr_p = addr_p->ai_next)
+ {
+ sock = socket(addr_p->ai_family,
+ addr_p->ai_socktype,
+ addr_p->ai_protocol);
+
+ if (sock != -1)
+ {
+ if (connect(sock, addr_p->ai_addr, addr_p->ai_addrlen) == -1)
+ {
+ close(sock);
+ sock = -1;
+ }
+ }
+ }
- if (connect(sock,(void*)&addr,sizeof(addr))==-1)
+ if (sock == -1)
{
- perror(name);
- exit(EXIT_FAILURE);
+ fprintf(stderr, "%s: Failed to connect to %s:%s\n", name, n, p);
+ exit(EXIT_FAILURE);
}
return sock;
@@ -111,7 +123,7 @@ int main(int argc, char *argv[])
no_write = 0;
}
- sock = Connect(argv[1],atoi(argv[2]));
+ sock = Connect(argv[1],argv[2]);
/* Test to see how to get the connected local port number
*/