Skip to content

Instantly share code, notes, and snippets.

@mutoe
Created March 7, 2023 05:36
Show Gist options
  • Save mutoe/70eb21b21beb9b5b1461c93846bb26ed to your computer and use it in GitHub Desktop.
Save mutoe/70eb21b21beb9b5b1461c93846bb26ed to your computer and use it in GitHub Desktop.
Get IP address
const http = require('http')
function getClientIp (req) {
const forwardedIpsStr = req.headers['x-forwarded-for']
if (forwardedIpsStr) {
console.log('forwardedIpsStr: ' + forwardedIpsStr)
return forwardedIpsStr.split(',')[0]
}
console.log('remoteAddress: ' + req.connection.remoteAddress)
return req.connection.remoteAddress
}
const server = http.createServer((req, res) => {
res.writeHead(200)
res.end(getClientIp(req))
})
server.listen(3001, () => {
console.log('IP Address service is listening on port 3001...')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment