メインコンテンツにスキップ

クライアントの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://developer.mozilla.org/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://developer.mozilla.org/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);
});