joyent/node — Issue #2273: dgram: close on unbound socket will call close(-1)
Author: mamikk
Created: 2011-12-05 15:42:14+00:00
State: open

Node v0.6.5 seems to close dgram sockets when the bind()-call fails, this is fine I guess but when one explicitly closes the socket later with close() it will call close() with -1 as an argument which isn't a valid file descriptor but it shouldn't do this in any case or at least the documentation should be updated explaining that one shouldn't call close() on sockets where bind() has failed.

This test case:

var dgram = require('dgram');

var sock1 = dgram.createSocket('udp4');
sock1.bind(12345, '127.0.0.1');

var sock2 = dgram.createSocket('udp4');
sock2.on('error', function(err) {}); /* Eliminate the exception. */
sock2.bind(12345, '127.0.0.1');

sock1.close();
sock2.close();

Will result in the following when run under strace:

socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 6
ioctl(6, FIONBIO, [1]) = 0
fcntl(6, F_SETFD, FD_CLOEXEC) = 0
bind(6, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 7
ioctl(7, FIONBIO, [1]) = 0
fcntl(7, F_SETFD, FD_CLOEXEC) = 0
bind(7, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EADDRINUSE (Address already in use)
close(7) = 0
close(6) = 0
close(4294967295) = -1 EBADF (Bad file descriptor)