Chris Dutrow Chris Dutrow - 1 year ago 118
Javascript Question

IP Address Parser in Javascript

Looking for a good IP address parser for Javascript.

Ideally, it could take in an IP address as a string, then return an object containing all of the pieces of the IP Address, including the port.


Answer Source
var v4 = '[\\d]{1-3}';
var v4d = '\\.';
var v4complete = v4+v4d+v4+v4d+v4+v4d+v4
var v6 = '[\\da-fA-F]{0-4}';
var v6d = ':';
var v6complete = v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6+v6d+v6;
var regex = new RegExp('(' + v4complete + '(\\:\d+){0,1}|'
                           + '::|::1|'
                           + '\\[::\\]:\\d+|\\[::1\\]:\\d+|'
                           + v6complete + '|'
                           + '\\[' + v6complete + '\\]:\\d+' + ')', 'g');
var result = mystring.match(regex);

Note that this doesn't guarantee valid addresses (in the range 0-255 for IPv4, for example). But it should match ip's with or without the port.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download