Node.js socket.remoteAddress() Method
Last Updated :
06 Apr, 2023
The socket.remoteAddress() method is an inbuilt application programming interface of class Socket within dgram module which is used to get the remote address of the server containing the port, address, and family.
Syntax:
const socket.remoteAddress()
Parameters: This method does not accept any parameters.
Return Value: This method returns the remote address of the server containing the port, address, and family.
Example 1: In this example, we will see the use of the socket.remoteAddress() Method
Filename: index.js
Javascript
const dgram = require( 'dgram' );
let client = dgram.createSocket( "udp4" );
let server = dgram.createSocket( "udp4" );
server.on( "message" , function (msg) {
process.stdout.write( "UDP String: " + msg + "\n" );
process.exit();
});
server.on( 'listening' , () => {
const address = server.address();
console.log(`server listening
${address.address}:${address.port}`);
});
server.bind(1234, () => {
server.connect(1234, "localhost" , () => {
console.log( "connected" );
const add = server.remoteAddress();
console.log(add);
});
});
client.send( "Hello" , 0, 7, 1234, "localhost" );
|
Output:
server listening 0.0.0.0:1234
connected
{ address: '127.0.0.1', family: 'IPv4', port: 1234 }
Example 2: If the server is not connected.
Filename: index.js
Javascript
const dgram = require( 'dgram' );
let client = dgram.createSocket( "udp4" );
let server = dgram.createSocket( "udp4" );
server.on( "message" , function (msg) {
process.stdout.write( "UDP String: " + msg + "\n" );
process.exit();
});
server.on( 'listening' , () => {
const address = server.address();
console.log(`server listening
${address.address}:${address.port}`);
});
server.bind(1234, () => {
const add = server.remoteAddress();
console.log(add);
});
client.send( "Hello" , 0, 7, 1234, "localhost" );
|
Output:
node GFG.js
server listening 0.0.0.0:1234
dgram.js:745
throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
^
Error [ERR_SOCKET_DGRAM_NOT_CONNECTED]: Not connected
at Socket.remoteAddress (dgram.js:745:11)
at Socket.<anonymous> (F:\java\GFG.js:42:28)
at Socket.onListening (dgram.js:225:10)
at Socket.emit (events.js:327:22)
at startListening (dgram.js:150:10)
at dgram.js:345:7
at processTicksAndRejections (internal/process/task_queues.js:85:21) {
code: 'ERR_SOCKET_DGRAM_NOT_CONNECTED'
}
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_remoteaddress
Share your thoughts in the comments
Please Login to comment...