Dgram : UDP network module
This module provides dgram operations compatible with Node.js.
User can use the following code to import the dgram
module.
var dgram = require('dgram');
Support
The following shows dgram
module APIs available for each permissions.
User Mode | Privilege Mode | |
---|---|---|
dgram.createSocket | ● | ● |
socket.close | ● | ● |
socket.bind | ● | ● |
socket.connect | ● | ● |
socket.disconnect | ● | ● |
socket.address | ● | ● |
socket.remoteAddress | ● | ● |
socket.send | ● | ● |
socket.setTTL | ● | ● |
socket.bindToDevice | ● | ● |
socket.setBroadcast | ● | ● |
socket.getRecvBufferSize | ● | ● |
socket.getSendBufferSize | ● | ● |
socket.setRecvBufferSize | ● | ● |
socket.setSendBufferSize | ● | ● |
socket.ref | ● | ● |
socket.unref | ● | ● |
socket.setMulticastInterface | ● | ● |
socket.setMulticastLoopback | ● | ● |
socket.setMulticastTTL | ● | ● |
socket.addMembership | ● | ● |
socket.addSourceSpecificMembership | ● | ● |
socket.dropMembership | ● | ● |
socket.dropSourceSpecificMembership | ● | ● |
Dgram.Socket Class
dgram.createSocket(options[, callback])
options
{Object} Options.callback
{Function} Attached as a listener for'message'
events. Optional.- Returns: {Object}
dgram.Socket
object.
Creates a dgram.Socket
object. Once the socket is created, calling socket.bind()
will instruct the socket to begin listening for datagram messages. When address
and port
are not passed to socket.bind()
the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both udp4
and udp6
sockets). The bound address and port can be retrieved using socket.address().address
and socket.address().port
.
options
can contain the following members:
type
{String} The family of socket. Must be either'udp4'
or'udp6'
. Required.fd
{Integer} Use this file descriptor to create.reuseAddr
{Boolean} Whentrue
socket.bind()
will reuse the address, even if another process has already bound a socket on it. default: false.ipv6Only
{Boolean} Settingipv6Only
totrue
will disable dual-stack support, i.e., binding to address::
won't make0.0.0.0
be bound. default: false.recvBufferSize
{Integer} Sets theSO_RCVBUF
socket value.sendBufferSize
{Integer} Sets theSO_SNDBUF
socket value.lookup
{Function} Custom lookup function. default:dns.lookup(hostname[, domain], callback)
.
Example
var socket = dgram.createSocket({ type: 'udp4' });
dgram.createSocket(type[, callback])
type
{String} The family of socket. Must be either'udp4'
or'udp6'
.callback
{Function} Attached as a listener for'message'
events. Optional.- Returns: {Object} Dgram socket object.
Creates a dgram.Socket
object of the specified type
. Once the socket is created, calling socket.bind()
will instruct the socket to begin listening for datagram messages. When address
and port
are not passed to socket.bind()
the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both udp4
and udp6
sockets). The bound address and port can be retrieved using socket.address().address
and socket.address().port
.
Example
var socket = dgram.createSocket('udp4');
Dgram.Socket Object
socket.close([callback])
callback
{Function} Called when the socket has been closed.
Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the 'close'
event.
Example
var socket = dgram.createSocket('udp4');
socket.close();
socket.bind([port][, address][, callback])
port
{Integer} Port.address
{String} Local address.callback
{Function} with no parameters. Called when binding is complete.
For UDP sockets, causes the dgram.Socket
to listen for datagram messages on a named port
and optional address
. If port
is not specified or is 0
, the operating system will attempt to bind to a random port. If address
is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening'
event is emitted and the optional callback
function is called.
Specifying both a 'listening'
event listener and passing a callback
to the socket.bind()
method is not harmful but not very useful.
A bound datagram socket keeps the JSRE process running to receive datagram messages.
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.
Example of a UDP server listening on port 3333
:
Example
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(3333);
// Prints: server listening 0.0.0.0:3333
socket.bind(options[, callback])
options
{Object} Binding options.callback
{Function} with no parameters. Called when binding is complete.
For UDP sockets, causes the dgram.Socket
to listen for datagram messages on a named port
and optional address
that are passed as properties of an options
object passed as the first argument. If port
is not specified or is 0
, the operating system will attempt to bind to a random port. If address
is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening'
event is emitted and the optional callback
function is called.
options
can contain the following members:
port
{Integer} Port.address
{String} Local address.fd
{Integer} Change file descriptor to socket file.
The options
object may contain a fd
property. When a fd
greater or equal than 0
is set, it will wrap around an existing socket with the given file descriptor. In this case, the properties of port
and address
will be ignored.
Specifying both a 'listening'
event listener and passing a callback
to the socket.bind()
method is not harmful but not very useful.
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.
Example
socket.bind({
address: 'localhost',
port: 8000
});
socket.connect(port[, address][, callback])
port
{Integer} Port.address
{String} Local address.callback
{Function} Called when the connection is completed or on error.
Associates the dgram.Socket
to a remote address and port. Every message sent by this handle is automatically sent to that destination. Also, the socket will only receive messages from that remote peer. If address is not provided, '127.0.0.1'
(for udp4
sockets) or '::1'
(for udp6
sockets) will be used by default. Once the connection is complete, a 'connect'
event is emitted and the optional callback
function is called. In case of failure, the callback
is called or, failing this, an 'error'
event is emitted.
Example
socket.connect(8000);
socket.disconnect()
A synchronous function that disassociates a connected dgram.Socket
from its remote address.
socket.address()
- Returns: {Object} This socket address info.
Returns an object containing the address information for a socket. For UDP sockets, this object will contain address
, family
and port
properties.
Example
console.log('udp on port:', socket.address().port);
socket.remoteAddress()
- Returns: {Object} This socket remote address info.
Returns an object containing the address
, family
, and port
of the remote endpoint.
socket.send(msg[, offset, length][, port][, address][, callback])
msg
{Buffer | String | Array} Message to be sent.offset
{Integer} Offset in the buffer where the message starts.length
{Integer} Number of bytes in the message.port
{Integer} Destination port.address
{String} Destination host name or IP address.callback
{Function} Called when the message has been sent.
Broadcasts a datagram on the socket. For connectionless sockets, the destination port
and address
must be specified. Connected sockets, on the other hand, will use their associated remote endpoint, so the port
and address
arguments must not be set.
The msg
argument contains the message to be sent. Depending on its type, different behavior can apply. If msg is a Buffer
the offset
and length
specify the offset within the Buffer
where the message begins and the number of bytes in the message, respectively. If msg
is a String
, then it is automatically converted to a Buffer
with 'utf8'
encoding. With messages that contain multi-byte characters, offset
and length
will be calculated with respect to byte length and not the character position. If msg
is an Array
, offset
and length
must not be specified.
The address
argument is a string. If the value of address
is a host name, DNS will be used to resolve the address of the host. If address
is not provided or otherwise falsy, '127.0.0.1'
(for udp4
sockets) or '::1'
(for udp6
sockets) will be used by default.
If the socket has not been previously bound with a call to bind, the socket is assigned a random port number and is bound to the "all interfaces" address ('0.0.0.0'
for udp4
sockets, '::0'
for udp6
sockets.)
An optional callback
function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the buf
object. DNS lookups delay the time to send for at least one tick of the JSRE event loop.
The only way to know for sure that the datagram has been sent is by using a callback
. If an error occurs and a callback is given, the error will be passed as the first argument to the callback
. If a callback
is not given, the error is emitted as an 'error'
event on the socket object.
Offset and length are optional but both must be set if either are used. They are supported only when the first argument is a Buffer
.
Example
- Example of sending a UDP packet to a port on localhost;
const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 3333, 'localhost', (err) => {
client.close();
});
- Example of sending a UDP packet composed of multiple buffers to a port on
127.0.0.1
;
const dgram = require('dgram');
const buf1 = Buffer.from('Some ');
const buf2 = Buffer.from('bytes');
const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 3333, (err) => {
client.close();
});
- Example of sending a UDP packet using a socket connected to a port on
localhost
:
const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.connect(3333, 'localhost', (err) => {
client.send(message, (err) => {
client.close();
});
});
socket.setTTL(timeToLive)
timeToLive
{Integer} IP TTL: 0 ~ 255.- Returns: {Boolean} Whether the operation was successful.
Sets the IP_TTL
socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.
socket.bindToDevice([ifname])
ifname
{String} Network interface name. default: all network interface.- Returns: {Boolean} Whether the operation was successful.
The socket.bindToDevice()
function binds the network sending and receiving to the specified network interface, and the data packet is only allowed to be sent and received using this network interface.
Example
socket.bindToDevice('en1');
socket.setBroadcast(enable)
enable
{Boolean} Whether to enable broadcast.- Returns: {Boolean} Whether the operation was successful.
Sets or clears the SO_BROADCAST
socket option. When set to true, UDP packets may be sent to a local interface's broadcast address.
socket.getRecvBufferSize()
- Returns: {Integer} Receive buffer size, negative on error.
Get current receive buffer size in bytes.
socket.getSendBufferSize()
- Returns: {Integer} Send buffer size, negative on error.
Get current send buffer size in bytes.
socket.setRecvBufferSize(size)
size
{Integer} Receive buffer size. Must be between 1024bytes and 16Mbytes.- Returns: {Boolean} Whether the operation was successful.
Set current receive buffer size in bytes.
socket.setSendBufferSize(size)
size
{Integer} Send buffer size. Must be between 1024bytes and 16Mbytes.- Returns: {Boolean} Whether the operation was successful.
Set current send buffer size in bytes.
socket.ref()
- Returns: {Object} This
dgram.Socket
object.
This object reference, the system will not recycle this object.
socket.unref()
- Returns: {Object} This
dgram.Socket
object.
This object unreference.
socket.setMulticastInterface(multicastInterface)
multicastInterface
{String} Multicast network interface name.- Returns: {Boolean} Whether the operation was successful.
Set the specified udp multicast network interface.
Example
socket.setMulticastInterface('wl3');
socket.setMulticastTTL(timeToLive)
timeToLive
{Integer} IP TTL: 0 ~ 255.- Returns: {Boolean} Whether the operation was successful.
Changes the specified udp TTL value of the multicast IP header.
Example
socket.setMulticastTTL(8);
socket.setMulticastLoop(enable)
enable
{Boolean} Whether to enable multicast loop.- Returns: {Boolean} Whether the operation was successful.
Set the specified udp whether to allow multicast loop.
Example
socket.setMulticastLoop(false);
socket.addMembership(multicastAddr[, multicastInterface])
multicastAddr
{String} Multicast address.multicastInterface
{String} Multicast network interface name. default: all interface.- Returns: {Boolean} Whether the operation was successful.
Use the socket.addMembership()
to join an multicast group on a interface.
Example
socket.addMembership('224.0.1.222', 'en1');
socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])
sourceAddress
{String} Source addressgroupAddress
{String} Multicast address.multicastInterface
{String} Multicast network interface name. default: all interface.- Returns: {Boolean} Whether the operation was successful.
Use the socket.addSourceSpecificMembership()
to join an multicast group on a interface.
Example
socket.addSourceSpecificMembership('192.168.1.1', '224.0.1.222', 'en1');
socket.dropMembership(multicastAddr[, multicastInterface[, sourceAddr]])
multicastAddr
{String} Multicast address.multicastInterface
{String} Multicast network interface name. default: all interface.- Returns: {Boolean} Whether the operation was successful.
Use the socket.dropMembership()
to leave an multicast group on a interface.
Example
socket.dropMembership('224.0.1.222', 'en1');
socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])
sourceAddress
{String} Source addressgroupAddress
{String} Multicast address.multicastInterface
{String} Multicast network interface name. default: all interface.- Returns: {Boolean} Whether the operation was successful.
Use the socket.dropSourceSpecificMembership()
to leave an multicast group on a interface.
Example
socket.dropSourceSpecificMembership('192.168.1.1', '224.0.1.222', 'en1');