/// <include file='doc\IPAddress.uex' path='docs/doc[@for="IPAddress.Parse"]/*' />
/// <devdoc>
/// <para>Converts an IP address string to an <see cref='System.Net.IPAddress'/>
/// instance.</para>
/// </devdoc>
public static IPAddress Parse(string ipString)
{
if (ipString == null)
{
throw new ArgumentNullException("ipString");
}
//
// IPv6 Changes: Detect probable IPv6 addresses and use separate
// parse method.
//
if (ipString.IndexOf(':') != -1)
{
//
// If the address string contains the colon character
// then it can only be an IPv6 address. Use a separate
// parse method to unpick it all. Note: we don't support
// port specification at the end of address and so can
// make this decision.
//
// We need to make sure that Socket is initialized for this
// call !
//
bool ipv6 = Socket.SupportsIPv6;
SocketAddress saddr = new SocketAddress(AddressFamily.InterNetworkV6, 28);
int errorCode =
UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress(
ipString,
AddressFamily.InterNetworkV6,
IntPtr.Zero,
saddr.m_Buffer,
ref saddr.m_Size);
if (errorCode != SocketErrors.Success)
{
GlobalLog.Print("IPAddress::Parse() IPv6 ipString:[" + ValidationHelper.ToString(ipString) + "] errorCode: " + errorCode.ToString());
throw new FormatException(SR.GetString(SR.dns_bad_ip_address), new SocketException());
}
//
// We have to set up the address by hand now, to avoid initialization
// recursion problems that we get if we use IPEndPoint.Create.
//
byte[] bytes = new byte[16];
long scope = 0;
for (int i = 0; i < 16; i++)
{
bytes[i] = saddr[i + 8];
}
//
// Scope
//
scope = (long)((saddr[27] << 24) +
(saddr[26] << 16) +
(saddr[25] << 8) +
(saddr[24]));
return(new IPAddress(bytes, scope));;
}
else
{
//
// Cannot be an IPv6 address, so use the IPv4 routines to
// parse the string representation.
//
int address = UnsafeNclNativeMethods.OSSOCK.inet_addr(ipString);
GlobalLog.Print("IPAddress::Parse() ipString:" + ValidationHelper.ToString(ipString) + " inet_addr() returned address:" + address.ToString());
if (address == -1 &&
string.Compare(ipString, InaddrNoneString, false, CultureInfo.InvariantCulture) != 0 &&
string.Compare(ipString, InaddrNoneStringHex, true, CultureInfo.InvariantCulture) != 0 &&
string.Compare(ipString, InaddrNoneStringOct, false, CultureInfo.InvariantCulture) != 0)
{
throw new FormatException(SR.GetString(SR.dns_bad_ip_address));
}
IPAddress returnValue = new IPAddress(address);
return(returnValue);
}
} // Parse