Created
April 25, 2012 14:12
-
-
Save lucidfrontier45/2489986 to your computer and use it in GitHub Desktop.
sample program for getaddrinfo and inet_atop
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 <stdio.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
typedef struct sockaddr_in SA4; | |
typedef struct sockaddr_in6 SA6; | |
int main(int argc, char **argv){ | |
char *hostname = argv[1]; | |
char *service = argv[2]; | |
struct addrinfo hints, *res0, *res; | |
int err; | |
int sock; | |
char paddr[128]; | |
memset(&hints, 0, sizeof(hints)); | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_family = AF_UNSPEC; | |
if ((err = getaddrinfo(hostname, service, &hints, &res0)) != 0) { | |
printf("error %d\n", err); | |
return 1; | |
} | |
if (res0 == NULL) { | |
printf("failed\n"); | |
return 1; | |
} | |
for (res=res0; res!=NULL; res=res->ai_next) { | |
if(res->ai_family == AF_INET ){ | |
SA4 *socaddr_v4 = (SA4 *)res->ai_addr; | |
inet_ntop(res->ai_family, &(socaddr_v4->sin_addr), paddr, 128); | |
printf("%s %d\n", paddr, ntohs(socaddr_v4->sin_port)); | |
} | |
if(res->ai_family == AF_INET6 ){ | |
SA6 *socaddr_v6 = (SA6 *)res->ai_addr; | |
inet_ntop(res->ai_family, &(socaddr_v6->sin6_addr), paddr, 128); | |
printf("%s %d\n", paddr, ntohs(socaddr_v6->sin6_port)); | |
} | |
} | |
freeaddrinfo(res0); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment