Question : How to find my ip address (Winsock)

I've written a Winsock2 program that tries to be a client connecting to a remote computer. If that fails, it tries to be a server running on the local computer. The reason it works this way is to allow it to run in a user-friendly way on two computers that are connected via the Internet.

This much seems to work, when tested locally using 'localhost'.

In order to make this work across the net to a remote computer, I need my program to find out my IP address. I can then send this information to a person at the remote computer for them to use when running my program on their computer. Their copy of the program will then communicate, as a client, with the copy that is running on my computer, as a server.

My IP may be static or dynamic, and may be LAN or dialup. In particular, my IP may be dynamically assigned during dialup. That is why I said "I need my program to find out my IP address".

I would prefer to use Winsock and/or Win32, not MFC, not ISAPI, not Wininet, etc.

I develop using VC++ v.6 on Win 98.

David

Answer : How to find my ip address (Winsock)

With due respect, perhaps you posted this question in the wrong area of Experts-Exchange.  The question would probably be better answered if it were in the programming section of the site.  Mrclean gave you a place to look, (the registry) and a path to that place (do a find on your IP address), but it is from the network perspective which is understandable since this is the networking area of the site.

I'm not a developer, but isn't calling registry values a pretty basic function when developing Windows apps?

Saying that, this is not my code and it is for VC++ 5, but this may help you.

// Borland C++ 5.0: bcc32.cpp getlocalip.cpp
// Visual C++ 5.0: cl getlocalip.cpp wsock32.lib
//
// This sample program is hereby placed in the public domain.

#include
#include

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;
}


Random Solutions  
 
programming4us programming4us