We help IT Professionals succeed at work.

Obtaining a machines IP Address

johnclarke
johnclarke asked
on
I need a routine that gets the IP address of the machine that the program is currently running on.  The compiler that I am using is Microsoft Visual C Version 6.

I would be grateful for all advice offered regarding this.

Thanks in advance

John
Comment
Watch Question

CERTIFIED EXPERT

Commented:
struck sockaddr_in our_addr;
char buffer[255];
gethostname(buffer,sizeof(buffer));
struct hostent *host = gethostbyname(buffer);
memcpy((char*)&our_addr.sin_addr,host->h_addr,host->h_length);

then to convert to dotted decimal

char * inet_ntoa(our_addr.sin_addr);

dont free the pointer that the above function returns as its from winsocks own heap and winsock maanages that. also if you want the ip address make sure you make a pysical copy of it to another memory location as the next winsock call may overwrite the original (see the winsock help for more info on this)
CERTIFIED EXPERT
Commented:
#include <iostream.h>
#include <winsock.h>

int doit(int, char **)
{
    char ac[80];
    if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
        cerr << "Error " << WSAGetLastError() <<
                " when getting local host name." << endl;
        return 1;
    }
    cout << "Host name is " << ac << "." << endl;

    struct hostent *phe = gethostbyname(ac);
    if (phe == 0) {
        cerr << "Yow! Bad host lookup." << endl;
        return 1;
    }

    for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
        struct in_addr addr;
        memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
        cout << "Address " << i << ": " << inet_ntoa(addr) << endl;
    }
   
    return 0;
}

int main(int argc, char *argv[])
{
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
        return 255;
    }

    int retval = doit(argc, argv);

    WSACleanup();

    return retval;
}

Explore More ContentExplore courses, solutions, and other research materials related to this topic.