Skip to content

Commit c7167c6

Browse files
authored
Implement IP address validation in server.js
1 parent 6a6f96c commit c7167c6

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

server-src/server.js

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,47 @@ function closeUserFromUserSocket(username) {
8383
console.log(e);
8484
}
8585
}
86+
87+
function isPrivateIp(ip) {
88+
if (!ip) return false;
89+
90+
// Handle IPv6 localhost
91+
if (ip === '::1' || ip === 'localhost') return true;
92+
93+
// Split the IP into its 4 parts (octets)
94+
const parts = ip.split('.');
95+
if (parts.length !== 4) return false; // Not a standard IPv4 address
96+
97+
const first = parseInt(parts[0], 10);
98+
const second = parseInt(parts[1], 10);
99+
100+
// 127.x.x.x (Localhost)
101+
if (first === 127) return true;
102+
103+
// 10.x.x.x (Private network)
104+
if (first === 10) return true;
105+
106+
// 192.168.x.x (Private network)
107+
if (first === 192 && second === 168) return true;
108+
109+
// 172.16.x.x through 172.31.x.x (Private network)
110+
if (first === 172 && second >= 16 && second <= 31) return true;
111+
112+
return false;
113+
}
86114
function getIPFromRequest(req) {
87-
if (req.headers["x-forwarded-for"]) {
88-
var IPString = "" + req.headers["x-forwarded-for"];
115+
var ipListHeader = req.headers['x-forwarded-for'];
116+
if (ipListHeader) {
117+
var IPString = "" + ipListHeader;
89118
var IPs = IPString.split(",").map((ip) => ip.trim());
90-
return IPs[0];
119+
var i = IPs.length-1;
120+
while (i > 0) {
121+
var curIp = IPs[i];
122+
if (!isPrivateIp(curIp)) {
123+
return curIp;
124+
}
125+
i -= 1;
126+
}
91127
}
92128
return req.socket.remoteAddress;
93129
}

0 commit comments

Comments
 (0)