jornane
jornane

Reputation: 1515

Set local address for client socket in Node.JS

In my Node.JS application, I initiate a TCP connection to a nearby server.

clientSocket = new net.Socket({});
clientSocket.connect(12345, ip, function () { … });

The socket uses the primary address of eth0, but eth0 has multiple addresses (within the same subnet). Is it possible to define the local address the socket should use?

Upvotes: 0

Views: 2573

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

If you use the factory method which returns a net.Socket, net.createConnection, you can do this.

var net = require('net');

var socket = net.createConnection({
    port: 10011,
    host: 'localhost',
    localAddress: '192.168.0.1'
}, function() {
    console.log('connected');
});

Documentation

Upvotes: 2

Related Questions