summaryrefslogtreecommitdiff
path: root/sock.c
diff options
context:
space:
mode:
authorIan C <ianc@noddybox.co.uk>2021-05-02 21:59:52 +0000
committerIan C <ianc@noddybox.co.uk>2021-05-02 21:59:52 +0000
commit9c665db210078f81eddef85fb4d2ca0263e5ce06 (patch)
treeee4076dffd147c6ac35d1aed33e5b7e67ad33562 /sock.c
parent675bc29a6b426c1485bd5705683de64f0d1c7188 (diff)
Added IPv6 support to sock.c
Diffstat (limited to 'sock.c')
-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
*/