-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
160 additions
and
2 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import forwardedParse from "forwarded-parse"; | ||
import { isIP } from "is-ip"; | ||
import { Socket } from "socket.io"; | ||
|
||
/** | ||
* Given a socket, returns the IP address of the client. | ||
* | ||
* This function will try to find the most accurate IP address, based on headers and other data. | ||
*/ | ||
export function getClientIp(socket: Socket): string { | ||
return ( | ||
checkedIp(getXForwardedFor(socket)) || | ||
checkedIp(getForwarded(socket)) || | ||
checkedIp(getCloudflareHeaders(socket)) || | ||
socket.handshake.address | ||
); | ||
} | ||
|
||
function checkedIp(ip: string | undefined) { | ||
return ip && isIP(ip) ? ip : undefined; | ||
} | ||
|
||
function getXForwardedFor(socket: Socket) { | ||
return [socket.handshake.headers["x-forwarded-for"] ?? []] | ||
.flat() | ||
.map((forwardedFor) => forwardedFor.split(",")[0]?.trim()) | ||
.filter(Boolean)[0]; | ||
} | ||
|
||
function getForwarded(socket: Socket) { | ||
try { | ||
const forwardedHeader = socket.handshake.headers["forwarded"]; | ||
return forwardedHeader | ||
? forwardedParse(forwardedHeader)[0]?.for | ||
: undefined; | ||
} catch { | ||
return undefined; | ||
} | ||
} | ||
|
||
function getCloudflareHeaders(socket: Socket) { | ||
return socket.handshake.headers["cf-connecting-ip"]?.[0]; | ||
} |