How to advertise server IP on the network?

I am developing an application consisting of a server made in NodeJS that should provide data in JSON to clients, in case an application for Android, all running on internal network.

I have already managed to do the entire communication process and everything works as expected, but I am setting the IP and Port of the server in a fixed way both on the server and on the client (for example 192.168.1.15:3300).

I would like to know if there is a way of announce the IP of the server on the network since it can change at some point, such as in online games, where a list of connected servers is shown.

I have already thought about doing a scan of my server port across the network, but this process can become slow, even more so that the client may not have much processing power.

Is there any faster or better way to "advertise" the IP of the server on the network so that clients can connect?

Author: Renato Gama, 2014-12-23

2 answers

Peter, in fact scouring the network looking for the service / device is infeasible, especially if you can't use something like nmap (with some binding to nodejs) on the client device.

My suggestion is that you do not implement anything on hand and use already known protocols for this purpose, for example SSDP.

The simple service discovery protocol (SSDP) is a network protocol of the set of internet protocols, for dissemination and discovery of network services and information presence. it accomplishes this goal without assistance from server-based configuration mechanisms, such as DHCP or DNS , and without static settings . SSDP is the basis of the discovery protocol of the Universal Plug and Play (UPnP).

SSDP is a protocol based on HTTPU which is an extension of HTTP 1.1 using the UDP as transport layer.

The server advertises the service available by doing IP multicast for the port 1900. The multicast address range is 239.0.0.0 - 239.255.255.255. The verb HTTP NOTIFY is used to announce or notify the deactivation of a service.

For a client to discover services available on a network the verb M-SEARCH is used and responses to these requests are returned in unicast (one-to-one communication) to the same address and port that originated it.

Clarifying

In your application architecture both clients (smartphones) and the server will listen and send messages. Initially, when no one knows no one there can be two situations:

1-the server just joined the network, suppose your server just came back from a reboot - it then multicast for everyone on the network, on Port 1900 with UDP, sending a verb NOTIFY, with all the information network location (ip and Port). Customers (smartphones) who are already listening on Port 1900 receive the request and from there use this information as they see fit.

2-a new client has just joined the network and wants to discover the server. It then sends a multicast to Port 1900, with the verb M-SEARCH. The server receives this request and returns the request to the same originating address and port, the client receives the return and does as it sees fit with the information.

Why use all this?

So you don't have the need to create your own service discovery protocol and don't waste time developing libraries that already handle it. Node already has modules that abstract this type of problem and I bet there are libraries for smartphones that also already do.

How to implement all this?

1-you implement everything in hand, or
2 - you can use the module super-ssdp which is super simple and has a lowercase API:

var ssdp = require('super-ssdp'),
    ip = require('ip'),
    porta = (Math.random() * 10000).toFixed(0), // Porta fake. Coloque aqui a porta do seu serviço principal
    peer = ssdp.createPeer({
        name: 'suaAplicação',
        url: 'http://' + ip.address() + ':' + porta
    });

peer.start();

peer.on('found', function(endereco) {
    console.log('Serviço encontrado!', endereco);
});

To test the above code you need to do the following; npm install super-ssdp ip and then node app.js (or the file name you prefer). Now open another terminal (to simulate another device) and run the last command again. Preferably test on another computer connected to the network.

More Tests

Let's test that any customer, smartphone in your case, is able to find the server.

In one terminal tab turn the above code, in another turn this

var dgram = require('dgram'),
    ip = require('ip');

//0- Este é o nosso request HTTPU
var msearch = new Buffer(
    'M-SEARCH * HTTP/1.1\r\n' +
    'HOST:239.255.255.250:1900\r\n' +
    'MAN:\"ssdp:discover\"\r\n' +
    'ST:ssdp:all\r\n' +
    'MX:3\r\n' +
    '\r\n'
);

//1- Criamos um socket para enviar o M-SEARCH e escutar a resposta
var client = dgram.createSocket('udp4');

//2- Este socket escuta numa porta que o proprio SO vai designar,
//   e em todos os endereços, não apenas localhost
client.bind(function() {
    client.on('message', function(msg, rinfo) {
        //3- Aqui trataremos a reposta
        if(rinfo.address !== ip.address()) {
            //4- Só estamos interessados em mensagens vindas do localhost.
            //   Se você não colocar este `if` você vai receber varias mensagens
            //   do seu roteador, por exemplo!
            return;
        }

        //5- Imprimimos a resposta que contem o IP e porta do servidor.
        //   O ideal aqui seria fazer um parse da resposta.
        console.log(msg.toString());
    });

    //6- Enviamos o M-SEARCH para todo mundo, repare a porta e o endereço multicast
    client.send(msearch, 0, msearch.length, 1900, '239.255.255.250', function() {
        console.log('M-SEARCH enviado...');
    });
});

In the above code we have implemented in hand the code of an SSDP client, which is precisely what the library for Android or iOS should do for you.

We could even implement another test where Server 2 sends a NOTIFY to server1 but the library super-ssdp did not implement the handler for NOTIFY then there is no way to test. Actually this library is not consolidated, the only like it has on GitHub is my KKK - you'll probably want to find something more tested and consolidated, sometimes something even outside the node itself and then you just create the bindings.

Your problem (or not ) will be to find a library that implements SSDP in the language / platform of smartphones.

 9
Author: Renato Gama, 2014-12-24 06:10:30

As it is internal network I think the simplest would be the server to drop a UDP broadcast (or multicast) packet at regular intervals "announcing" its existence.

Maybe these links will help:

 5
Author: PerryWerneck, 2017-05-23 12:37:23