如何获取客户端的 IP 地址
直接连接
客户端的 IP 地址可以在 handshake
对象中找到
io.on("connection", (socket) => {
const ipAddress = socket.handshake.address;
console.log(ipAddress); // prints something like "203.0.113.195" (IPv4) or "2001:db8:85a3:8d3:1319:8a2e:370:7348" (IPv6)
});
位于代理后面
如果您位于像 nginx 这样的代理后面,address
属性将是代理的 IP 地址。
在这种情况下,客户端的 IP 地址将在请求头中找到。
X-Forwarded-For
头部
X-Forwarded-For
请求头是用于识别通过代理服务器连接到 Web 服务器的客户端的原始 IP 地址的事实上的标准头。
参考:https://mdn.org.cn/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
格式
X-Forwarded-For: <client>, <proxy1>, <proxy2>
以下是如何检索客户端的 IP 地址
io.on("connection", (socket) => {
const ipAddress = socket.handshake.headers["x-forwarded-for"].split(",")[0];
console.log(ipAddress);
});
X-Forwarded-For
头部现在已弃用(尽管仍然被广泛使用),取而代之的是标准的 Forwarded
头部。
Forwarded
头部
Forwarded
请求头是用于识别通过代理服务器连接到 Web 服务器的客户端的原始 IP 地址的标准头。
参考:https://mdn.org.cn/en-US/docs/Web/HTTP/Headers/Forwarded
格式
Forwarded: by=<identifier>;for=<identifier>;host=<host>;proto=<http|https>
以下是如何检索客户端的 IP 地址
function parseHeader(header) {
for (const directive of header.split(",")[0].split(";")) {
if (directive.startsWith("for=")) {
return directive.substring(4);
}
}
}
io.on("connection", (socket) => {
const ipAddress = parseHeader(socket.handshake.headers["forwarded"] || "");
console.log(ipAddress);
});
此 parseHeader()
方法并未涵盖规范允许的每个边缘情况。如果您需要更强大的方法,请查看 forwarded-parse
包。
CloudFlare
CloudFlare 使用一个特定的头:cf-connecting-ip
参考:https://developers.cloudflare.com/fundamentals/reference/http-request-headers/
以下是如何检索客户端的 IP 地址
io.on("connection", (socket) => {
const ipAddress = socket.handshake.headers["cf-connecting-ip"];
console.log(ipAddress);
});
Fastly
Fastly 使用一个特定的头:fastly-client-ip
参考:https://developer.fastly.com/reference/http/http-headers/Fastly-Client-IP/
以下是如何检索客户端的 IP 地址
io.on("connection", (socket) => {
const ipAddress = socket.handshake.headers["fastly-client-ip"];
console.log(ipAddress);
});