Created
May 2, 2020 06:12
-
-
Save saleebm/9c992f3baa4594fec93d888b1491c6ac to your computer and use it in GitHub Desktop.
Get a public ip address from client on server
This file contains hidden or 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
const LOCAL_IPV4_REGEX = /(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/ | |
const LOCAL_IPV6_REGEX = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/ | |
export function getClientIPAddress() { | |
let addrInfo, ifaceDetails | |
let localIPInfo: string = '' | |
//Get the network interfaces | |
const networkInterfaces = require('os').networkInterfaces() | |
//Iterate over the network interfaces | |
for (let ifaceName in networkInterfaces) { | |
ifaceDetails = networkInterfaces[ifaceName] | |
//Iterate over all interface details | |
for (let _i = 0, _len = ifaceDetails.length; _i < _len; _i++) { | |
addrInfo = ifaceDetails[_i] | |
if ( | |
addrInfo.family === 'IPv4' && | |
LOCAL_IPV4_REGEX.test(addrInfo.address) | |
) { | |
localIPInfo = addrInfo.address | |
} else if ( | |
addrInfo.family === 'IPv6' && | |
LOCAL_IPV6_REGEX.test(addrInfo.address) | |
) { | |
if (!addrInfo.address.startsWith('fe80')) { | |
localIPInfo = addrInfo.address | |
} | |
} | |
} | |
} | |
return localIPInfo | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment