Get IP Address of an Host
From Code Trash
Here are various ways to get the ip address of an hostname in dot seperated string. Also there are other functions which fetches the needful.
You can replace the function alert with your own I/O function.
Contents
gethostbyname - option 1
struct hostent *pHost; pHost = gethostbyname("vikku.info"); alert(pHost->h_addr); in_addr * address=(in_addr * )pHost->h_addr; alert(inet_ntoa(* address));
gethostbyname - option 2
hostent* localHost; char* localIP; localHost = gethostbyname("vikku.info"); localIP = inet_ntoa (*(struct in_addr *)*localHost->h_addr_list); alert(localIP);
gethostbyname - option 3
struct hostent *host = gethostbyname("www.google.com"); struct in_addr *ptr = (struct in_addr *) host->h_addr_list[0]; int nOct1 = ptr->S_un.S_un_b.s_b1; int nOct2 = ptr->S_un.S_un_b.s_b2; int nOct3 = ptr->S_un.S_un_b.s_b3; int nOct4 = ptr->S_un.S_un_b.s_b4; ... char *pIPAddr = inet_ntoa(*ptr);
gethostbyname - By directly iterating
char ctrl[3] = {'\r','\n','\0'}; struct hostent *pHost; unsigned char ip,i,j; string str; char ipc[6]; str=""; pHost = gethostbyname("google.com"); for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) { for(j=0; j<pHost->h_length; j++) { ip = (unsigned char)pHost->h_addr_list[i][j]; str += itoa(ip,ipc,10); str += "."; } str+=ctrl; } alert(str);
gethostbyname - casting the list by unsigned long
struct hostent *pHost; pHost = gethostbyname("vikku.info"); in_addr a; a.s_addr = *(unsigned long*)pHost->h_addr_list[0]; alert(inet_ntoa(a));
Discussion
http://www.codeproject.com/Messages/3369019/h_addr_list-of-gethostbyname-returns-negative-valu.aspx