views:

869

answers:

2

I'm using IPAddress.TryParse() to parse IP addresses. However, it's a little too permissive (parsing "1" returns 0.0.0.1). I'd like to limit the input to dotted octet notation. What's the best way to do this?

(Note: I'm using .NET 2.0)


Edit

Let me clarify:

I'm writing an app that will scan a range of IPs looking for certain devices (basically a port scanner). When the user enters "192.168.0.1" for the starting address, I want to automatically fill in "192.168.0.255" as the ending address. The problem is that when they type "1", it parses as "0.0.0.1" and the ending address fills in as "0.0.0.255" - which looks goofy.

A: 

An IP address is actually a 32 bit number - it is not xxx.xxx.xxx.xxx - that's just a human readable format for the same. So IP address 1 is actually 0.0.0.1.

EDIT: Given the clarification, you could either go with a regex as has been suggested, or you could format the short cuts to your liking, so if you want "1" to appears as "1.0.0.0". you could append that and still use the parse method.

Brian Rasmussen
Right, but when the user typed "1", he didn't likely mean "0.0.0.1".
Jon B
+5  A: 

If you are interested in parsing the format, then I'd use a regular expression. Here's a good one (source):

bool IsDottedDecimalIP(string possibleIP)
{
    Regex R = New Regex(@"\b(?:\d{1,3}\.){3}\d{1,3}\b");
    return R.IsMatch(possibleIP) && Net.IPAddress.TryParse(possibleIP, null);
}

That regex doesn't catch invalid IPs but does enforce your pattern. The TryParse checks their validity.

Michael Haren
This is probably the best way, but remember that it will not accept IPv6...
chills42
Doesn't compile for me... invalid escape characters. I'm too much of a regex n00b to debug :(
Jon B
Regex.IsMatch(SubjectString, "\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b")
Diadistis
or @"\b(?:\d{1,3}\.){3}\d{1,3}\b" or "\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b"
Diadistis
@Diadistis - I tried that and it didn't work, but turns out I was also passing the wrong string. I guess you need to get everything right at the same time :)
Jon B
Thanks, Jon--I always forget the "@" on this site.
Michael Haren