c++linuxsocketsberkeley-sockets

How to make a .cpp file to act as an accessible server


I have written a simple program with Linux (Cent OS 7.0) and C++. It is a very small server which sends back a string of characters to the client. But my problem is that I don't know how should I access that server using an IP address?

I have used Linux Socket Interface (Berkeley), and in the section which defines the address, my code does the following:

    serverObject.
            sin_family = AF_INET;
    serverObject.sin_addr.
            s_addr = htonl(INADDR_ANY);
    serverObject.
            sin_port = htonl(portNumber);

I use INADDR_ANY as my server's address which is defined in its definition as:

/* Address to accept any incoming messages.  */

Now, how should I run the server, and then use my simple client program to send request to it. My simple client program accepts an IP address as it's destination address, this address should be the one destined toward to the server. How should I relate it then?


Solution

  • INADDR_ANY goes to specify that all active network interfaces in the system should be bound to. So if you're connected to more than one network, you'll be able to communicate with connections coming in from all of them. Most systems will usually have just one, though, and this still goes to say that if the IP bound to that interface happens to change, you'll still bind to that interface.

    So, once you specify INADDR_ANY, you need to initiate connections according to the following rules:

    1. If you're connecting from the same physical machine, the easiest thing would be to use the loopback interface (127.0.0.1). However, you can still do (2).
    2. If you're connecting from another machine, you need to pick the accessible IP address of your server from that machine. As said above, if your server is only connected to one network, this will simply be the IP address of the server. Within an internal network this will often be something like 192.168.x.y, or 10.0.x.y—but it doesn't have to.
    3. If you're connecting from a different network which uses a gateway to access your server, then you will need to set up port forwarding in the relevant routers so that when they receive connection to port X, they will know to internally transfer it to your server.