I often need to convert a string IP to an Int32 and then back again. To facilitate converting an Int32 to its string representation I have added this extension method to my IntExtensions class in C#:
public static class IntExtensions
{
/// <summary>
/// Converts an integer that represents an IPv4 to the string equivalent
/// Source: http://guyellisrocks.com/coding/converting-a-string-ip-to-an-int-and-back/
/// </summary>
/// <param name="solidIP">The integer representation of an IPv4</param>
/// <returns>A string of the format x.x.x.x representing an IPv4</returns>
public static string ToIPv4(this int solidIP)
{
byte ip1 = (byte)(solidIP >> 24);
byte ip2 = (byte)(solidIP >> 16);
byte ip3 = (byte)(solidIP >> 8);
byte ip4 = (byte)(solidIP);
return ip1 + "." + ip2 + "." + ip3 + "." + ip4;
}
}
And to convert the string representation of an IP to an Int32 I have added this extension method to my StringExtensions class:
public static class StringExtensions
{
/// <summary>
/// Converts a string that holds an IPv4 address with the pattern x.x.x.x
/// to the integer equivalent. If the string cannot be split into 4 parts
/// using a . or if the 4 parts cannot by parsed
/// into bytes then 0 will be returned.
/// Source: http://guyellisrocks.com/coding/converting-a-string-ip-to-an-int-and-back/
/// </summary>
/// <param name="IP">A string representing an IPv4 address</param>
/// <returns>An integer representing an IPv4 address or zero if failure</returns>
public static int ToIPv4(this string IP)
{
try
{
string[] fourIP = IP.Split('.');
Int32 ip =
(Byte.Parse(fourIP[0]) << 24) +
(Byte.Parse(fourIP[1]) << 16) +
(Byte.Parse(fourIP[2]) << 8) +
Byte.Parse(fourIP[3]);
return ip;
}
catch
{
return 0;
}
}
}
No comments:
Post a Comment