首页 > 开发 > NodeJS > 正文

Nodejs获取IPv4地址

2018-02-23 20:50:04  来源:XY

问题

node 版本8.9.0

使用req.connection.remoteAddress 获取的地址形如:::ffff:127.0.0.1的ipV6地址

解决

将原来的

app.listen(port)

改为

app.listen(port,'0.0.0.0')

分析

->官方文档

server.listen([port][, hostname][, backlog][, callback])#

Added in: v0.1.90

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. Omit the port argument, or use a port value of 0, to have the operating system assign a random port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.

To listen to a unix socket, supply a filename instead of port and hostname.

Backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512).

This function is asynchronous. callback will be added as a listener for the 'listening' event. See also net.Server.listen(port).