12

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!

6
  • 6
    An IP address has no Port, what are you really trying to parse? an URL? Commented Feb 11, 2013 at 22:51
  • I'm not an expert, but this community seems to think that port handling should be included in an IP Parser: rosettacode.org/wiki/Parse_an_IP_Address Commented Feb 11, 2013 at 22:56
  • 2
    @ChrisDutrow That community has its terms confused. While connecting to a remote host over TCP/UDP does require an IP address/port pair, the two are distinct conceptually. Commented Feb 11, 2013 at 23:09
  • 1
    @ChrisDutrow That's specific to the particular usage. IP Addresses do not include a port number themselves, but an application can group them together for its own purposes. In the case of window.location, this is the host, made up of the hostname (IP Address) and port. Commented Feb 11, 2013 at 23:12
  • 1
    I cannot fathom why this has so many upvotes? Simply because I don't see what are the "pieces of the IP address" - that's just a bunch of numbers - so what? What's the point of this excercise? An IP address is a number, big deal. I'm really just curious. Commented Feb 11, 2013 at 23:14

4 Answers 4

2
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.

Sign up to request clarification or add additional context in comments.

3 Comments

Monkey wrench: ::1 and :: are valid IPv6 addresses. "Loopback" and "unspecified," respectively. :)
@JonathanLonowski, how about now?
Not quite. All leading 0s are optional, including 0800:00db -> 800:db. :: just implies a "group of 0s." /([\da-f]{0,4}(:{1,2}[\da-f]{0,4}){1,7})/i (regexpal) could be a crude start that can catch many "clearly invalid" cases. It does mismatch multiple uses of :: and probably other cases.
2
 function parseIP(ip) {
   if(ip.match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3})/)!=null)  {
     ip = ip.match(/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/);  //clean posible port or http://
      return ip.split(".");   //returns [a,b,c,d] array
   }
   else 
      return false;
 }

That will do it. Split method splits string by delimiter. Its opposite is Array.join(delimiter), which joins the array with optional delimiter between the pieces.

4 Comments

This might work, but I would think the poster would like something a little more robust. When asking for a parser, he's probably expecting more than just tokenizing, in my opinion.
Well, I will let him leave comment, of he wants anything more. Meanwhile, I'll add IPv6 parsing.
This would fail to parse the "port" -- whatever that may be.
Well, I think I have to introduce regular expressions anyway. On the ather side, noone talked about ports here. With such process, we will end up with parsing whole tcp request won't we?
1

I came across this question while implementing Safe Browsing url canonicalization in JS. The answers here are helpful, and here's some JS I came up with that does octal & hex IP addresses, in case it's helpful to anyone else in the future:

function verifyIP4(address) {
  var ip4DecimalPattern = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$';
  var ip4HexPattern = '^(?:(?:0x[0-9a-f]{1,2})\.){3}(?:0x[0-9a-f]{1,2})$';
  var ip4OctalPattern = '^(?:(?:03[1-7][0-7]|0[12][0-7]{1,2}|[0-7]{1,2})\.){3}(?:03[1-7][0-7]|0[12][0-7]{1,2}|[0-7]{1,2})$';

  var isIP4Decimal = isIP4Hex = isIP4Octal = false;
  var base = 10;

  isIP4Decimal = address.match(ip4DecimalPattern) != null;
  isIP4Hex = address.match(ip4HexPattern) != null;
  isIP4Octal = address.match(ip4OctalPattern) != null;

  if (isIP4Hex || isIP4Octal) {
    if (isIP4Hex) {
      base = 16;
    } else if (isIP4Octal) {
      base = 8;
    }
    return address.split('.').map(num => parseInt(num, base)).join('.');
  }
  return false;
}

Comments

0

This is what I came up with.

  • It parses the old kind of IP addresses, not the new IPv6.
  • It also does not do validation which would only be a hindrance for my use case.

::

// REGEX to break an ip address into parts
var ip_regex = /(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?::(\d+))?/ig;

// Parse the ip string into an object containing it's parts
var parse_ip_address = function(ip_string){

    // Use Regex to get the parts of the ip address
    var ip_parts = ip_regex.exec(ip_string);

    // Set ip address if the regex executed successfully
    if( ip_parts && ip_parts.length > 6 ){
        // Set up address object to elements in the list
        var ip_address = {
            'A':     ip_parts[1],
            'B':     ip_parts[2],
            'C':     ip_parts[3],
            'D':     ip_parts[4],
            'E':     ip_parts[5],
            'port':  ip_parts[6]
        }
        // Would rather not fiddle with 'undefined' value
        if( typeof ip_parts[5] != 'undefined') {
            ip_address[5] = null;
        }
    }

    // Return object
    return ip_parts;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.