Skip to content

Instantly share code, notes, and snippets.

@yuikns
Created August 24, 2013 14:53
Show Gist options
  • Save yuikns/6328582 to your computer and use it in GitHub Desktop.
Save yuikns/6328582 to your computer and use it in GitHub Desktop.
linux socket programming
#include <cstring> //memset
#include <sys/socket.h>
#include <netdb.h> //hostent
#include <arpa/inet.h>
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
bool hostname_to_ip(string host, string& ip);
int main(int argc,char *argv[])
{
if(argc <2)
{
cout << "Please provide a hostname to resolve" << endl;
return -1;
}
string hostname(argv[1]);
string ip;
bool status = hostname_to_ip(hostname , ip);
if(!status)
{
cout << "failed :" << endl;
}
else
{
cout << "success:" << endl <<
"host\t:" << hostname << endl <<
"ip \t:" << ip << endl;
}
return 0;
}
bool hostname_to_ip(string hostname, string& ip)
{
struct hostent *he;
struct in_addr **addr_list;
int i;
if ( (he = gethostbyname( hostname.c_str() ) ) == NULL)
return false;
addr_list = (struct in_addr **) he->h_addr_list;
for(i = 0; addr_list[i] != NULL; i++)
{
//Return the first one;
//ip = string(inet_ntoa(*addr_list[i]));
// AF_INET6
// ONLY SUPPORT IPv4
char str[INET_ADDRSTRLEN];
ip = string(inet_ntop(AF_INET,addr_list[i],str,INET_ADDRSTRLEN));
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment