简体   繁体   中英

IP address parsing in .NET

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM