the regular socket API (socket, accept, connect, send, recv, listen, bind, ...) is supported both by posix and MS compilers, so it's safe to assume portability to a large number of systems.
gethostbyname() returns a hostent struct pointer. Examine field h_addr_list
http://www.opengroup.org/onlinepubs/...s/netdb.h.html
Code:
#include <iostream>
#include <cstring>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
typedef unsigned long ip_t;
ip_t* gethostaddr(const char *hn,ip_t* ips = NULL,uint sz = 0){
static const unsigned int IPBSSZ = 1024;
static ip_t ipbs[IPBSSZ];
if(ips==NULL){ ips=ipbs;sz=IPBSSZ; }
else if(sz==0) return NULL;
else if(sz==1){ *ips=0;return ips; }
struct hostent *hostinfo = gethostbyname(hn);
if(hostinfo!=NULL){
uint k, szip = ((signed)sizeof(ip_t))>hostinfo->h_length?hostinfo->h_length:sizeof(ip_t);
for(k=0;hostinfo->h_addr_list[k] && k+1<sz && k<(IPBSSZ-1);k++){
memcpy(ips+k,hostinfo->h_addr_list[k],szip);
ips[k] = ntohl(ips[k]);
}
ips[k]=0;
}else{//probably was an ip
ips[0]=inet_addr(hn);
ips[1]=0;
}
return ips;
}
const char* inet_ipttoa(ip_t ip, char*b = NULL){
static char ips[22];
if(b==NULL) b=ips;
sprintf(b,"%u.%u.%u.%u",(uint)((ip>>24)&0xff),(uint)((ip>>16)&0xff),(uint)((ip>>8)&0xff),(uint)((ip>>0)&0xff));
return b;
}
int main(){
ip_t* ips = gethostaddr("www.google.com");
while( *ips )
std::cout<<inet_ipttoa(*ips++)<<std::endl;
return 0;
}
output
Code:
66.249.87.104
66.249.87.99
to get the ips of your computer, use it's network name.