We recently did some improvements on the elmah.io UI making IPs clickable. We’ve had automatic detection of IPs for a while but it always bugged me that the regex that we had didn’t caught IP addresses with a port number (typically logged by ASP.NET MVC and similar):

127.0.0.1:80

The solution was an improved piece of JavaScript to detect this that I’m sharing in hope of helping others with a similar challenge:

function resolveIP(data) {
    if (data) {
        if(data.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)(?:\:(?:\d|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/g)) {
            if(data.match(/:/g)) {
                var split = data.split(':');
                return split[0];
            }
            return data;
        }
    }
    return null;
}

You can find all sorts of regex matching IP addresses on the web. The regex above also support including a port number as seen in the example above. If the data value matches the regex, we return the IP part.

#javascript #ip #programming

Split IP and port in JavaScript with regular expressions
6.25 GEEK