Skip to content

Instantly share code, notes, and snippets.

@dreamcat4
Last active August 29, 2015 14:04
Show Gist options
  • Save dreamcat4/86706bba25c468fc0ecc to your computer and use it in GitHub Desktop.
Save dreamcat4/86706bba25c468fc0ecc to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* man getaddrinfo */
int main()
{
struct addrinfo *addrinfo = NULL;
struct addrinfo *rp = NULL;
struct addrinfo hints;
struct addrinfo res;
int err;
memset((void*)&hints, 0, sizeof(hints));
// hints.ai_family = PF_INET4;
// hints.ai_family = PF_INET6;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
err = getaddrinfo("localhost", "18083", &hints, &addrinfo);
if ( addrinfo )
{
for (rp = addrinfo; rp != NULL; rp = rp->ai_next)
{
int sa_family = ((struct sockaddr*)rp->ai_addr)->sa_family;
if ( sa_family == AF_INET6)
{
char straddr[INET6_ADDRSTRLEN];
struct sockaddr_in6* _ai_addr_ptr=(struct sockaddr_in6*)rp->ai_addr;
struct sockaddr_in6 _ai_addr=*_ai_addr_ptr;
inet_ntop(AF_INET6, &_ai_addr.sin6_addr, straddr, sizeof(straddr));
printf("%s\n", straddr);
}
else if ( sa_family == AF_INET)
{
printf("%s\n", inet_ntoa( ((struct sockaddr_in*)rp->ai_addr)->sin_addr ));
}
}
freeaddrinfo(addrinfo);
return(0);
}
else
{
printf("addrinfo->ai_family == 0x%x\n", addrinfo->ai_family);
}
if (err || !addrinfo)
{
printf("getaddrinfo failed with code %i.\n",err);
return(1);
}
printf("end_main()\n");
return (0);
}
@dreamcat4
Copy link
Author

Test results:

FreeBSD 9.2:

ums4 getaddrinfo/ root~# gcc test.c -o test && ./test
::1
127.0.0.1

Mac OS X 10.7 Lion:

janitors-man-mini getaddrinfo/ id~$ gcc test.c -o test && ./test
127.0.0.1
::1
fe80::1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment