-
-
Save shepmaster/8ffa98d5c30b02c4f770b58b47679fdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <arpa/inet.h> | |
int main(int argc, char *argv[]) { | |
while (1) { | |
int sockfd; | |
struct addrinfo hints, *servinfo, *p; | |
int rv; | |
memset(&hints, 0, sizeof hints); | |
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6 | |
hints.ai_socktype = SOCK_STREAM; | |
if ((rv = getaddrinfo("localhost", "7000", &hints, &servinfo)) != 0) { | |
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); | |
exit(1); | |
} | |
// loop through all the results and connect to the first we can | |
for(p = servinfo; p != NULL; p = p->ai_next) { | |
if ((sockfd = socket(p->ai_family, p->ai_socktype, | |
p->ai_protocol)) == -1) { | |
perror("socket"); | |
continue; | |
} | |
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { | |
if (errno == ECONNREFUSED) { continue; } | |
perror("connect"); | |
exit(1); | |
} | |
break; // if we get here, we must have connected successfully | |
} | |
freeaddrinfo(servinfo); // all done with this structure | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment