public static IPAddress Parse(string ipString)这个是IPAddress类的一个静态方法,可以将 IP 地址字符串转换为 System.Net.IPAddress 实例。
// 参数:
// ipString:
// 包含 IP 地址(IPv4 使用以点分隔的四部分表示法,IPv6 使用冒号十六进制表示法)的字符串。
//
// 返回结果:
// 一个 System.Net.IPAddress 实例。它内部是这样的- public static IPAddress Parse(string ipString)
- {
- return InternalParse(ipString, false);
- }
复制代码 最终是调用.NET内部封转的方法,方法内容如下:- private static unsafe IPAddress InternalParse(string ipString, bool tryParse)
- {
- long num7;
- if (ipString == null)
- {
- if (!tryParse)
- {
- throw new ArgumentNullException("ipString");
- }
- return null;
- }
- if (ipString.IndexOf(':') != -1)
- {
- SocketException innerException = null;
- if (Socket.OSSupportsIPv6)
- {
- byte[] buffer = new byte[0x10];
- SocketAddress address = new SocketAddress(AddressFamily.InterNetworkV6, 0x1c);
- if (UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(ipString, AddressFamily.InterNetworkV6, IntPtr.Zero, address.m_Buffer, ref address.m_Size) == SocketError.Success)
- {
- for (int i = 0; i < 0x10; i++)
- {
- buffer[i] = address[i + 8];
- }
- return new IPAddress(buffer, (((address[0x1b] << 0x18) + (address[0x1a] << 0x10)) + (address[0x19] << 8)) + address[0x18]);
- }
- if (tryParse)
- {
- return null;
- }
- innerException = new SocketException();
- }
- else
- {
- int start = 0;
- if (ipString[0] != '[')
- {
- ipString = ipString + ']';
- }
- else
- {
- start = 1;
- }
- int end = ipString.Length;
- fixed (char* str2 = ((char*) ipString))
- {
- char* name = str2;
- if (IPv6AddressHelper.IsValidStrict(name, start, ref end) || (end != ipString.Length))
- {
- uint num5;
- ushort[] numArray = new ushort[8];
- string scopeId = null;
- fixed (ushort* numRef = numArray)
- {
- IPv6AddressHelper.Parse(ipString, numRef, 0, ref scopeId);
- }
- if ((scopeId == null) || (scopeId.Length == 0))
- {
- return new IPAddress(numArray, 0);
- }
- if (uint.TryParse(scopeId.Substring(1), NumberStyles.None, null, out num5))
- {
- return new IPAddress(numArray, num5);
- }
- }
- }
- if (tryParse)
- {
- return null;
- }
- innerException = new SocketException(SocketError.InvalidArgument);
- }
- throw new FormatException(SR.GetString("dns_bad_ip_address"), innerException);
- }
- Socket.InitializeSockets();
- int length = ipString.Length;
- fixed (char* str3 = ((char*) ipString))
- {
- char* chPtr2 = str3;
- num7 = IPv4AddressHelper.ParseNonCanonical(chPtr2, 0, ref length, true);
- }
- if ((num7 == -1L) || (length != ipString.Length))
- {
- if (!tryParse)
- {
- throw new FormatException(SR.GetString("dns_bad_ip_address"));
- }
- return null;
- }
- return new IPAddress(((num7 & 0xffL) << 0x18) | (((num7 & 0xff00L) << 8) | (((num7 & 0xff0000L) >> 8) | ((long) ((num7 & 0xff000000L) >> 0x18)))));
- }
复制代码 一般开发中我们不需要知道.NETFrameWork的内部工作原理,微软为我们封转好了,我们直接在此基础上编程调用即可,这也是面向对象的好处!
|