因为.Net中没有了IP输入框这样的控件,所以对IP的输入和解析我们都只能自己来。.Net给我们提供了一个方便的IP地址处理类:IPAddress,它不仅能用于IPv4,还能处理IPv6的IP地址。不仅.Net如此,Winsock2也给我们提供了inet_addr函数可以用来解析IP地址。
  但当我们使用IPAddress.Parse或inet_addr函数来解析IP时,问题出现了:填入“192.168.0.1”没问题,但填入一个“192.168.0.09”就报错了,而“192.168.0.01”却是对的!这里的错误我想大家也都猜到了,就是系统解析时把“09”当成了八进制(以程序中八进制以0开头),当然八进制中是没有“09”这个数字的!其实在我们平常习惯里,比如在设置网卡IP时,IP的某一节数字前加几个0是完全可以的,系统将自动忽略多余的0。
  MSDN中.Net的IPAddress.Parse函数没有提到这个问题,但inet_addr函数给出了详细的描述,参考一下吧:

Internet Addresses

Values specified using the ".'' notation take one of the following forms:
a.b.c.d a.b.c a.b a
When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the 4 bytes of an Internet address. When an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left.
The parts that make up an address in "." notation can be decimal, octal or hexadecimal as specified in the C language. Numbers that start with "0x" or "0X" imply hexadecimal. Numbers that start with "0" imply octal. All other numbers are interpreted as decimal.

Internet address value Meaning
"4.3.2.16" Decimal
"004.003.002.020" Octal
"0x4.0x3.0x2.0x10" Hexadecimal
"4.003.002.0x10" Mix
Note  The following notations are only used by Berkeley, and nowhere else on the Internet. For compatibility with their software, they are supported as specified.
When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right-most 2 bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host''
When a two-part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right-most 3 bytes of the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host''.
When only one part is given, the value is stored directly in the network address without any byte rearrangement.


  对于自编的IP地址输入及解析,一般需要注意的也就是数字前面的0了!所以使用IPAddress.Parse时一定要慎重处理字符串中的多余的0了,否则将给用户带来很多困惑:输入的是“192.168.0.010”,怎么解析保存后变成“192.168.0.8”了。
posted on 2005-05-09 21:25  小生杂谈  阅读(4018)  评论(3编辑  收藏  举报