Efrat Cohen
Efrat Cohen

Reputation: 97

UDP socket in node.js

I am trying to connect to an UDP socket on another computer using the UDP socket of node.js and I am getting the following error:

bind EADDRNOTAVAIL192.168.1.50;12345

I am using the following code:

var port = 12345;
   var host = "192.168.1.50";
   var sock = dgram.createSocket("udp4");
   sock.on("listening", function () {
       console.log("server listening ");
    });

    sock.on("error", function (err) {
        console.log("server error:\n" + err.stack);
        sock.close();
    });

    //start the UDP server with the radar port 12345
    sock.bind(port, host);

any help?

thanks

Upvotes: 4

Views: 10283

Answers (2)

SergeyA
SergeyA

Reputation: 62573

You can't bind to the remote server address! It doesn't matter what your server ip is, you should bind to one of your local interfaces. If you want to bind on all local interfaces, just bind like following:

 sock.bind(port);

Upvotes: 3

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

You can send UDP datagrams in the following way (Sample code)

var dgram = require('dgram');

var PORT = 12345;
var HOST = '192.168.1.50';
var message = new Buffer('Pinging');

var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
   if (err) throw err;
   console.log('UDP message sent to ' + HOST +':'+ PORT);
   client.close();
});

Reference: http://www.hacksparrow.com/node-js-udp-server-and-client-example.html

Upvotes: 1

Related Questions