Last active
April 9, 2016 03:03
-
-
Save mik30s/8dfbfb97191f63e71f6caa79475880db to your computer and use it in GitHub Desktop.
Display the IP addresses of a host using C++ and UNIX sockets
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 <iostream> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <cstdlib> | |
#include <string> | |
using namespace std; | |
int main() { | |
addrinfo serverinfo, *result, *ptr; | |
int ret = 0; | |
memset(&hints,0,sizeof(serverinfo)); | |
serverinfo.ai_family = AF_UNSPEC; // fill this struct partially | |
serverinfo.ai_socktype = SOCK_STREAM; | |
string input = ""; | |
cout << "Whats the host's name: "; | |
getline(cin,input); | |
if((ret = getaddrinfo(input.c_str(),NULL,&serverinfo,&result)) != 0){ | |
cerr << "getaddrinfo(): "<<input <<"-" << gai_strerror(ret) << "\n"; | |
return 0; | |
} | |
cout << "IP addresses for "<< input << endl; | |
// Loop through all the linked list of address and get the ip addresses | |
for(ptr = result; ptr != NULL; ptr = ptr->ai_next){ | |
void *addr; | |
string ipver; | |
if(p->ai_family == AF_INET){ | |
// IPv4 address | |
sockaddr_in *ipv4 = (sockaddr_in*)p->ai_addr; | |
addr = &(ipv4->sin_addr); | |
ipver = "IPv4"; | |
} | |
else{ | |
// IPv6 address | |
sockaddr_in6 *ipv6 = (sockaddr_in6*)p->ai_addr; | |
addr = &(ipv6->sin6_addr); | |
ipver = "IPv6"; | |
} | |
// use INET6_ADDRSTRLEN becuase we need it to big enough | |
// convert the ip from network(bits) to presentation(eg. 127.0.0.1) | |
char ipAddress[INET6_ADDRSTRLEN]; | |
inet_ntop(p->ai_family, addr, ipstr, sizeof(ipAddress)); | |
// print it out | |
cout << ipver <<" " << ipstr << endl; | |
} | |
// free the memory | |
freeaddrinfo(res); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment