Skip to content

Instantly share code, notes, and snippets.

@bikrone
Last active August 29, 2015 14:21
Show Gist options
  • Save bikrone/322160030406177e547c to your computer and use it in GitHub Desktop.
Save bikrone/322160030406177e547c to your computer and use it in GitHub Desktop.
/*
* main.c
*
* Created on: May 22, 2015
* Author: khanh
*/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
// check arguments count
if (argc != 2) {
fprintf(stderr, "No IP host provided\n");
return 1;
}
struct addrinfo hints, *receivedAddrInfo, *p;
// set address hints
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status;
if ((status = getaddrinfo(argv[1], NULL, &hints, &receivedAddrInfo))!=0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
char ipAddress[INET6_ADDRSTRLEN];
for (p = receivedAddrInfo; p!=NULL; p = p->ai_next) {
char *ipVersion;
void *addr;
if (p->ai_family == AF_INET) {
struct sockaddr_in *addr4 = (struct sockaddr_in *)p->ai_addr;
addr = &(addr4->sin_addr);
ipVersion = "IPv4";
} else {
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(addr6->sin6_addr);
ipVersion = "IPv6";
}
inet_ntop(p->ai_family, addr, ipAddress, sizeof ipAddress);
printf("%s: %s\n", ipVersion, ipAddress);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment