Get IP Address of an Host

From Code Trash
Jump to: navigation, search

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.

gethostbyname - option 1

    struct hostent *pHost;
    pHost = gethostbyname("");
    in_addr * address=(in_addr * )pHost->h_addr;
    alert(inet_ntoa(* address));

gethostbyname - option 2

     hostent* localHost;
     char* localIP;
     localHost = gethostbyname("");
     localIP = inet_ntoa (*(struct in_addr *)*localHost->h_addr_list);

gethostbyname - option 3

     struct hostent *host = gethostbyname("");
     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];
    pHost = gethostbyname("");
    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 += ".";

gethostbyname - casting the list by unsigned long

    struct hostent *pHost;
    pHost = gethostbyname("");
    in_addr a;
    a.s_addr =  *(unsigned long*)pHost->h_addr_list[0];