Node.js net.SocketAddress() Method
Last Updated :
21 Mar, 2023
Node.js Net module allows you to create TCP or IPC servers and clients. A TCP client initiates a connection request to a TCP server to establish a connection with the server.
Syntax: Below is the syntax for importing the Net module into your node js project:
const <Variable_Name> = require('node:net');
const Net_Module = require('node:net');
The net.SocketAddress() class provides us with the detailed address of the socket of the network. See the below syntax for calling the SocketAddress() constructor of the class:
Syntax:
const socket = new Net_Module.SocketAddress([options]);
Parameters:
- Options: It consists of the IP address, port, family, and flow label values. It is <object> type, and optional.
Return Value:
- socket.address: <string> Returns the IP address.
- socket.family: <string> Returns the family of IP address – ipv4/ipv6.
- socket.flowlabel : <number> Returns a number that is an ipv6 flow label.
- socket.port: <number> Returns the port number.
Steps to create Node.js Project:
Step 1: Run the following command in your terminal to set up your Node.js project package.json:
npm init
Step 2: Create an app.js file that describes the code.
Step 3: Now import the net module into your project. and start writing your code.
In case the net module is not installed in your system, you may use the below command to install the net module into the project:
npm i net
Example 1: Let’s create an object of the net.SocketAddress() class and print the object.
Javascript
const Net_Module = require( 'node:net' );
const object = new Net_Module.SocketAddress();
console.log(object);
|
Output:
SocketAddress {
address: '127.0.0.1',
port: 0,
family: 'ipv4',
flowlabel: 0
}
As you can see from the output, the object of the class consists of four properties and returns the default values for each of the properties.
Example 2: We are creating a custom option object and passing it to this constructor to know whether it changes the default values for all the properties or not.
Javascript
const Net_Module = require( 'node:net' );
const options = {
address: '142.38.75.36' ,
family: 'ipv4' ,
port:200
};
const object = new Net_Module.SocketAddress(options);
console.log(object);
|
Output:
SocketAddress {
address: '142.38.75.36',
port: 200,
family: 'ipv4',
flowlabel: 0
}
We have used a random IP and Port number and generated the Socket address for this Ip address.
Reference: https://nodejs.org/api/net.html#class-netsocketaddress
Share your thoughts in the comments
Please Login to comment...