Skip to content

Instantly share code, notes, and snippets.

@tiebingzhang
Created August 9, 2016 14:49
Show Gist options
  • Save tiebingzhang/71b7aa2b16f1561a237347a6cb1d86f2 to your computer and use it in GitHub Desktop.
Save tiebingzhang/71b7aa2b16f1561a237347a6cb1d86f2 to your computer and use it in GitHub Desktop.
getaddrinfo test, returns a list of IP addresses for a particular domain name
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUF_SIZE 500
int main(int argc, char *argv[]) {
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s, j;
size_t len;
ssize_t nread;
char buf[BUF_SIZE];
char *port="80";
if (argc < 2) {
fprintf(stderr, "Usage: %s host \n", argv[0]);
exit(EXIT_FAILURE);
}
/* Obtain address(es) matching host/port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(argv[1], port, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
printf("ip=%08x\n",(((struct sockaddr_in *)(rp->ai_addr))->sin_addr.s_addr));
}
freeaddrinfo(result); /* No longer needed */
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment