diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js index 09c5ba31f6c5b5..3fad9cf6c65cff 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -3,45 +3,58 @@ const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); -// IPv4 Test -const socket_ipv4 = dgram.createSocket('udp4'); -const family_ipv4 = 'IPv4'; - -socket_ipv4.on('listening', function() { - const address_ipv4 = socket_ipv4.address(); - assert.strictEqual(address_ipv4.address, common.localhostIPv4); - assert.strictEqual(typeof address_ipv4.port, 'number'); - assert.ok(isFinite(address_ipv4.port)); - assert.ok(address_ipv4.port > 0); - assert.strictEqual(address_ipv4.family, family_ipv4); - socket_ipv4.close(); -}); - -socket_ipv4.on('error', function(e) { - console.log('Error on udp4 socket. ' + e.toString()); - socket_ipv4.close(); -}); - -socket_ipv4.bind(0, common.localhostIPv4); - -// IPv6 Test -const localhost_ipv6 = '::1'; -const socket_ipv6 = dgram.createSocket('udp6'); -const family_ipv6 = 'IPv6'; - -socket_ipv6.on('listening', function() { - const address_ipv6 = socket_ipv6.address(); - assert.strictEqual(address_ipv6.address, localhost_ipv6); - assert.strictEqual(typeof address_ipv6.port, 'number'); - assert.ok(isFinite(address_ipv6.port)); - assert.ok(address_ipv6.port > 0); - assert.strictEqual(address_ipv6.family, family_ipv6); - socket_ipv6.close(); -}); - -socket_ipv6.on('error', function(e) { - console.log('Error on udp6 socket. ' + e.toString()); - socket_ipv6.close(); -}); - -socket_ipv6.bind(0, localhost_ipv6); +{ + // IPv4 Test + const socket = dgram.createSocket('udp4'); + + socket.on('listening', common.mustCall(() => { + const address = socket.address(); + + assert.strictEqual(address.address, common.localhostIPv4); + assert.strictEqual(typeof address.port, 'number'); + assert.ok(isFinite(address.port)); + assert.ok(address.port > 0); + assert.strictEqual(address.family, 'IPv4'); + socket.close(); + })); + + socket.on('error', (err) => { + socket.close(); + common.fail(`Unexpected error on udp4 socket. ${err.toString()}`); + }); + + socket.bind(0, common.localhostIPv4); +} + +{ + // IPv6 Test + const socket = dgram.createSocket('udp6'); + const localhost = '::1'; + + socket.on('listening', common.mustCall(() => { + const address = socket.address(); + + assert.strictEqual(address.address, localhost); + assert.strictEqual(typeof address.port, 'number'); + assert.ok(isFinite(address.port)); + assert.ok(address.port > 0); + assert.strictEqual(address.family, 'IPv6'); + socket.close(); + })); + + socket.on('error', (err) => { + socket.close(); + common.fail(`Unexpected error on udp6 socket. ${err.toString()}`); + }); + + socket.bind(0, localhost); +} + +{ + // Verify that address() throws if the socket is not bound. + const socket = dgram.createSocket('udp4'); + + assert.throws(() => { + socket.address(); + }, /^Error: getsockname EINVAL$/); +}