Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks!

like image 849
Chris Dutrow Avatar asked Feb 11 '13 22:02

Chris Dutrow


1 Answers

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.

like image 71
PinnyM Avatar answered Oct 12 '22 14:10

PinnyM