Sunday, September 8, 2024

Body Roundness Index BRI | ellipse model

Body Roundness Index (BRI) is a...

How plants could mine metals from the soil

Metals like nickel, crucial for...

How to Validate an IP Address

Programming LanguageHow to Validate an IP Address


Andy has some concerns about future proofing. In this case, he sends us some C# code that’s supposed to validate an IP address.

string[] address = StringTools.splitStr(IP, '.');
if (address.length < 4) {
        throw new Exception("Bad IP format : " + IP);           }

Andy writes: “IPv6 will never be a thing!”

It’s not just IPv6, of course. There are plenty of ways one might choose to represent an IP address that don’t use dot decimal notation- any 32 bit integer is potentially an IP address. But we usually represent the IP address this way. No, there’s another problem with this particular parser: it checks in address.length < 4.

Now, this is actually genius. You see, our choices are IPv4 (32 bits of addresses), or IPv6 (128 bits of addresses), but what if we only want, oh, I don’t know, 40 bits? Well, this code will think 555.192.168.0.1 is a perfectly valid IP address, and frankly, why shouldn’t it be? A perfect bridge between IPv4 and IPv6. I’d call it IPv5, except for the fact that we had to skip 5 because of weird reasons.

Also, C# already has a function for parsing IP addresses which also has the benefit of doing it correctly.

Check out our other content

Check out other tags:

Most Popular Articles