Site hosted by Angelfire.com: Build your free website today!

Connecting to a Server with a Dynamic IP Address

If you have a client/server application, and the server is being run on a 56k dialup connection, this means the servers IP address changes everytime you dialup.  So how can the client find it each time?

One solution is using a "Dynamic DNS" system.
Such a system is "www.no-ip.com"

They give you a domain name which will refer to your computer even as its IP address changes.

An example is "coolgame.no-ip.com"

The Code
I'm assuming borland c++ compiler 5.5 for Windows.  It will most likely work for other windows compilers.
Including <windows.h> should be sufficient to define all the data structures and functions that are used.

The first thing you need is to call WSAStartup().
This is very important because the later call to gethostbyname() cannot work without this having been called first.

So, create a sockaddr_in structure:
struct sockaddr_in ServerAddress;

Then fill in the fields:
ServerAddress.sin_family = PF_INET;
ServerAddress.sin_port = htons(1234); //assuming your application port is 1234

The next field is more complicated.
First create a hostent structure (stands for host entity):
struct hostent *he;

Then get the server info with gethostbyname():
he = gethostbyname("coolgame.no-ip.com");

We have to check for errors at this point, gethostbyname() returns NULL if it cannot find the domain name.
if (he == NULL)
{
    WSACleanup();
    return;
}


Now we have to convert the IP address into a usable format:
char serverip[64];
char tempstr[20];
strcpy(serverip, itoa(LOBYTE(LOWORD(*((DWORD*)he->h_addr))), tempstr, 10));
strcat(serverip, ".");
strcpy(serverip, itoa(HIBYTE(LOWORD(*((DWORD*)he->h_addr))), tempstr, 10));
strcat(serverip, ".");
strcpy(serverip, itoa(LOBYTE(HIWORD(*((DWORD*)he->h_addr))), tempstr, 10));
strcat(serverip, ".");
strcpy(serverip, itoa(HIBYTE(HIWORD(*((DWORD*)he->h_addr))), tempstr, 10));

The above piece of code was adapted from:
    http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20552424.html


Finally we can fill in that last field:
ServerAddress.sin_addr.s_addr = inet_addr(serverip);

Now the ServerAddress structure can be used to create a socket and so on.

After all this, the client can now connect to the dialup server even though it has a changing IP address. :-)

Coding-Home
Home