Skip to content

Instantly share code, notes, and snippets.

@olegwtf
Created September 26, 2014 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olegwtf/f8b752c8e16d1d5a2da2 to your computer and use it in GitHub Desktop.
Save olegwtf/f8b752c8e16d1d5a2da2 to your computer and use it in GitHub Desktop.
getaddrinfo
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char *sockname(int type) {
if (type == SOCK_STREAM) return "SOCK_STREAM";
if (type == SOCK_DGRAM) return "SOCK_DGRAM";
if (type == SOCK_RAW) return "SOCK_RAW";
return "UNKNOWN";
}
int main() {
struct addrinfo *res;
char addr[100];
if (getaddrinfo("google.com", NULL, NULL, &res) == 0) {
struct addrinfo *inf;
for (inf = res; inf != NULL; inf = inf->ai_next) {
printf("sock_type=%s\n", sockname(inf->ai_socktype));
printf("addr=%s\n",
inet_ntop(inf->ai_family, inf->ai_family == AF_INET ?
(void*)&((struct sockaddr_in*)(inf->ai_addr))->sin_addr :
(void*)&((struct sockaddr_in6*)(inf->ai_addr))->sin6_addr,
addr, 100
)
);
printf("---------------------------\n");
}
freeaddrinfo(res);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment