Categories
JavaScript Answers

How to get the client’s IP address in socket.io?

Spread the love

Sometimes, we want to get the client’s IP address in socket.io.

In this article, we’ll look at how to get the client’s IP address in socket.io.

How to get the client’s IP address in socket.io?

To get the client’s IP address in socket.io, we can use the socket.handshake.address property.

For instance, we write

const io = require('socket.io').listen(server);

io.sockets.on('connection', (socket) => {
  const {
    address
  } = socket.handshake;
  console.log(address.address, address.port);
});

to call io.sockets.on with 'connection' to listen for client connections.

Then callback runs when a client is connected.

In it, we use socket.handshake.address to get the client’s address.

And we use address.address to get the IP address and address.port to get the port used for the connection.

Conclusion

To get the client’s IP address in socket.io, we can use the socket.handshake.address property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *