• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24const assert = require('assert');
25const dgram = require('dgram');
26
27{
28  // IPv4 Test
29  const socket = dgram.createSocket('udp4');
30
31  socket.on('listening', common.mustCall(() => {
32    const address = socket.address();
33
34    assert.strictEqual(address.address, common.localhostIPv4);
35    assert.strictEqual(typeof address.port, 'number');
36    assert.ok(isFinite(address.port));
37    assert.ok(address.port > 0);
38    assert.strictEqual(address.family, 'IPv4');
39    socket.close();
40  }));
41
42  socket.on('error', (err) => {
43    socket.close();
44    assert.fail(`Unexpected error on udp4 socket. ${err.toString()}`);
45  });
46
47  socket.bind(0, common.localhostIPv4);
48}
49
50if (common.hasIPv6) {
51  // IPv6 Test
52  const socket = dgram.createSocket('udp6');
53  const localhost = '::1';
54
55  socket.on('listening', common.mustCall(() => {
56    const address = socket.address();
57
58    assert.strictEqual(address.address, localhost);
59    assert.strictEqual(typeof address.port, 'number');
60    assert.ok(isFinite(address.port));
61    assert.ok(address.port > 0);
62    assert.strictEqual(address.family, 'IPv6');
63    socket.close();
64  }));
65
66  socket.on('error', (err) => {
67    socket.close();
68    assert.fail(`Unexpected error on udp6 socket. ${err.toString()}`);
69  });
70
71  socket.bind(0, localhost);
72}
73
74{
75  // Verify that address() throws if the socket is not bound.
76  const socket = dgram.createSocket('udp4');
77
78  assert.throws(() => {
79    socket.address();
80  }, /^Error: getsockname EBADF$/);
81}
82