Skip to content

Instantly share code, notes, and snippets.

@robertoostenveld
Created September 3, 2017 20:17
Show Gist options
  • Save robertoostenveld/ecb56493963bb2e595a6e9455fc9eb38 to your computer and use it in GitHub Desktop.
Save robertoostenveld/ecb56493963bb2e595a6e9455fc9eb38 to your computer and use it in GitHub Desktop.
snippet of code to be inserted in interface.c to replace gethostbyname
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(host, "http", &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) {
s = -1;
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket");
continue;
}
// specify the port to connect to
p->ai_addr.sin_port = htons(port);
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
perror("connect");
close(sockfd);
continue;
}
break; // if we get here, we must have connected successfully
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
// looped off the end of the list with no connection
fprintf(stderr, "failed to connect\n");
s = -1;
}
else {
s = sockfd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment