0

Sorry, I'm quite new to network programming and nodejs. I'm using nodes in a server with some clients in a local network.

Sometimes I have to ask data to clients via get request:

// somewhere inside server.js
function askDataToClient(ip) {

    var options = {
        host: String(ip),
        port: 80,
        path: '/client/read',
        auth: 'username:password'
    };

    var request = http.get(options, function(htres){
        var body = "";
        htres.on('data', function(data) {
            body += data;
        });
        htres.on('end', function() {
            body = JSON.parse(body);
            res.json(body);
            res.end();
        })
        htres.on('error', function(e) {
            // ...
        });
    });
}

I'd like to know the server ip used for calling this get request.

I know of this answer but it gives me all the various network active on the server machine:

lo0 127.0.0.1
en1 192.168.3.60
bridge0 192.168.2.1

If I'm querying the client 192.168.3.36 I know it is the second ip, 192.168.3.60 because they are on the same network.. but How to know it programmatically?

Community
  • 1
  • 1
nkint
  • 11,513
  • 31
  • 103
  • 174

2 Answers2

2

You should be able to use htres.socket.address().address to get the IP.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • I would like to pass the ip address of the server as a value in the url.. like "ipclient/setserver/1.1.1.1" I know it sounds weird but it is a workaround around some embedded devices that does not support the PUT method, so I would do it before to construct the htres object – nkint May 26 '14 at 15:45
  • There is no easy/general way to know *before* performing the request because there could be any number of routing/iptables rules, etc. that would affect what IP is used to send the request. The only other option would be to manually set the `localAddress` option so you can specify which interface/IP to use for the request. – mscdex May 26 '14 at 16:20
  • is there any kind of workaround or pattern i can use? i'd like to notify all clients with the ip of the server. due to the fact both the clients and the server goes up and down the dhcp always changes them – nkint May 26 '14 at 18:50
1

Check out request.connection.remoteAddress property available for the HTTP Request object. This indicates the address of the remote host performing the request.

Errol Dsilva
  • 177
  • 11