I am trying to convert the following from Python to node.js. This is a simple program that uses a regular expression to check if the IP address is public or private:
import re def is_private_ip(ip): """ Returns `True` if the `ip` parameter is a private network address. """ c = re.compile('(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)') if c.match(ip): return True return False print is_private_ip('192.168.0.1')
I implemented it in Javascript as follows:
var localIp = new RegExp(/(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/); console.log('192.168.0.1'.match(localIp)); console.log('8.8.8.8'.match(localIp)); console.log('109.231.231.221'.match(localIp));
Which gives me the following result:
[ '192.168.', undefined, undefined, undefined, undefined, undefined, '192.168.', index: 0, input: '192.168.0.1' ] null null
It seems to me that it works (not even sure tbh). The two IP addresses that should be publicly return null , so I assume this is correct. However, I do not understand the result of another match? I could not find out what this means.
Juicy source share