pek
pek

Reputation: 18035

How to evaluate an IP?

How can I determine if a string is an IP address? Either IPv4 or IPv6?

What is the least and most number of characters?

I assume this would be a regex answer.

Upvotes: 9

Views: 3971

Answers (7)

mplungjan
mplungjan

Reputation: 178421

IPv4 address

Here is a pattern that will validate the format but not the logic

Hit enter to validate the format 999.999.999.999

I then incorporated an improved version of this answer to handle the logic

const isValidOctet = (num,index) => num <= 255 && (index < 2 ? num >= 1 : num >= 0);
window.addEventListener('DOMContentLoaded', () => {
  document.getElementById('txtSignDSCIPAdd').addEventListener('input', (e) => {
    const tgt = e.target;
    tgt.setCustomValidity('');
    const s = tgt.value.trim();
    const match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
    const valid = match != null &&
      isValidOctet(+match[1],0) && 
      isValidOctet(+match[2],1) && 
      isValidOctet(+match[3],2) && 
      isValidOctet(+match[4],3);
    if (match && !valid) {
      console.log(isValidOctet(match[0],valid,+match[1],0),isValidOctet(+match[2],1),isValidOctet(+match[3],2),isValidOctet(+match[4],3))
      tgt.setCustomValidity(`The entered IP address is not valid (match: ${match[0]}, valid: ${valid})`);
      tgt.reportValidity();
    }
  });
  // while testing
  document.querySelector('form').addEventListener('submit',(e) => { console.log('Submitted'); e.preventDefault() })

});
<form>
  <label for="">Signet/DSC IP Address</label>
  <span class="mandatory" style="color: red;">*</span>
  <input type="text" class="form-control" id="txtSignDSCIPAdd" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" required/>
</form>

Upvotes: 0

Michael Haren
Michael Haren

Reputation: 108376

Since half of that regex handles the fact that the last segment doesn't have a period at the end, you could cut it in half if you tack a '.' to the end of your possible IP address.

Something like this:

bool IsValidIPAddress(string possibleIP){
  CrazyRegex = \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){4}\b
  return Regex.Match(possibleIP+'.', CrazyRegex)
}

Upvotes: 0

Dough
Dough

Reputation: 7

IPv4 becomes: /\d\d?\d?.\d\d?\d?.\d\d?\d?.\d\d?\d?/

I'm not sure about the IPv6 rules.

Upvotes: -1

Michael Haren
Michael Haren

Reputation: 108376

In .NET there's an IPAddress type which has a handy method TryParse.

Example:

if(System.Net.IPAddress.TryParse(PossibleIPAddress, validatedIPAddress)){
    //validatedIPAddress is good
}

// or more simply:
bool IsValidIPAddress(string possibleIP){
    return System.Net.IPAddress.TryParse(PossibleIPAddress, null)
}

Upvotes: 6

Niniki
Niniki

Reputation: 810

I've done this before, but I like Raymond Chen's post at:

http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx

Where he basically advocates using regexes for what they're good at: parsing out the tokens. Then evaluate the results. His example:

function isDottedIPv4(s)
{
 var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
 return match != null &&
        match[1] <= 255 && match[2] <= 255 &&
        match[3] <= 255 && match[4] <= 255;
}

It's much easier to look at that and grok what it's supposed to be doing.

Upvotes: 6

UnkwnTech
UnkwnTech

Reputation: 90961

@unsliced that is correct however it will of course depend on implementation, if you are parsing an IP from a user visiting your site then your are fine to use regex as it SHOULD be in x.x.x.x format.

For IPv6 you could use this

[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}:[A-F0-9]{0,4}

however it does not catch everything because with IPv6 it is much more complicated, acording to wikipedia all of the following examples are technicaly correct however the regex above will only catch the ones with a *

2001:0db8:0000:0000:0000:0000:1428:57ab*
2001:0db8:0000:0000:0000::1428:57ab*
2001:0db8:0:0:0:0:1428:57ab*
2001:0db8:0:0::1428:57ab
2001:0db8::1428:57ab
2001:db8::1428:57ab

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 406125

For IPv4 you can use this regular expression.

\b(?:(?: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]?)\b

It looks quite complex but it works by limiting each quad to the numbers 0-255.

Upvotes: 4

Related Questions