Created
September 26, 2014 11:23
-
-
Save olegwtf/f8b752c8e16d1d5a2da2 to your computer and use it in GitHub Desktop.
getaddrinfo
This file contains hidden or 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 <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