1

I am working with UDP sockets, I am facing a certain issue that when a code is run for the first time it works, but when it is run for the second time it gives me this error:

at _handle.lookup (dgram.js:266:18)  
at _combinedTickCallback (internal/process/next_tick.js:142:11)
at process._tickCallback (internal/process/next_tick.js:181:9)

I deduced that this error is issued because the port is still in use, so I am trying to work on a sample code that checks if a socket is running on a certain port, if yes close it and then create the socket again on the same port.

Here is the sample code:

var PORT = 7777;
var HOST = '10.0.1.10';

var dgram = require('dgram');
var server = dgram.createSocket('udp4');

gener(server, PORT, HOST);

function gener(sock, prt, hst){
        sock.close();
        sock.bind(prt, hst);
}

server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

server.on('message', function (message, remote) {
    console.log(remote.address + ':' + remote.port +' - ' + message);

});

When I run it, it gives me the following error:

dgram.js:638
    throw new errors.Error('ERR_SOCKET_DGRAM_NOT_RUNNING');
    ^

Error [ERR_SOCKET_DGRAM_NOT_RUNNING]: Not running
    at Socket._healthCheck (dgram.js:638:11)
    at Socket.bind (dgram.js:186:8)
    at gener (/home/caracall/Desktop/server.js:11:18)
    at Object.<anonymous> (/home/caracall/Desktop/server.js:7:1)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
Caracalla
  • 27
  • 3

2 Answers2

1

This is the issue:

function gener(sock, prt, hst){
        sock.close();
        sock.bind(prt, hst);
}

You definitely can not close a socket and then expect "bind" to succeed immediately afterwards. You need to create new socket. You probably want something closer to this:

function gener(sock, prt, hst){
        if (sock) {
            sock.close();
            sock = null;
        }
        sock = dgram.createSocket('udp4');
        sock.bind(prt, hst);
}
selbie
  • 100,020
  • 15
  • 103
  • 173
0

You are attempting to bind with a closed socket, that's why Error ERR_SOCKET_DGRAM_NOT_RUNNING is thrown. Please refer to the Node.js document:

If binding fails, an 'error' event is generated. In rare case (e.g. attempting to bind with a closed socket), an Error may be thrown.

To check whether a certain port is occupied, and kill the owner process (dangerous operation), you can use kill-port:

const kill = require('kill-port');
kill(7777);
shaochuancs
  • 15,342
  • 3
  • 54
  • 62