c# - IP address validation -
i'm refactoring code , wanted use ipaddress.tryparse
method validate if string valid ipv4 address instead of using regular expressions:
public static bool isipv4(string value) { ipaddress address; if (ipaddress.tryparse(value, out address)) { if (address.addressfamily == addressfamily.internetwork) { return true; } } return false; }
my unit test failing because these input values return true
, parsed following ipaddress
objects:
value = "0.0.0.0" -> address = {0.0.0.0} value = "255.255.255" -> address = {255.255.0.255} value = "65536" -> address = {0.1.0.0}
does make sense? can see 0.0.0.0
technically valid ipv4 address, if makes no sense user enter that. other two? why converted in way , should treat them valid if might not transparent user, maybe forgot enter periods (65536
instead of 6.5.5.36
).
any appreciated.
it looks docs ipaddress.parse
rationalize behavior pointing out entering fewer parts convenient entering class , b addresses. if want force four-part address, might want check there 3 periods in address before feeding ipaddress.tryparse
, guess.
some code reference:
// verify ip consists of 4 parts if (value.split(new char[] { '.' }, stringsplitoptions.removeemptyentries).length == 4) { ipaddress ipaddr; if (ipaddress.tryparse(value, out ipaddr)) { // ip valid } else // invalid ip } else // invalid ip
Comments
Post a Comment