Konventiert eine IP-Adresse zu Long / Long zu IP-Adresse
public static long IPToLong(string ipAddress)
{
System.Net.IPAddress ip;
if (System.Net.IPAddress.TryParse(ipAddress, out ip))
return (((long)ip.GetAddressBytes()[0] << 24) | ((int)ip.GetAddressBytes()[1] << 16) | ((int)ip.GetAddressBytes()[2] << 8) | ip.GetAddressBytes()[3]);
else return 0;
}
public static string LongToIP(long ipAddress)
{
System.Net.IPAddress tmpIp;
if (System.Net.IPAddress.TryParse(ipAddress.ToString(), out tmpIp))
{
try
{
Byte[] bytes = tmpIp.GetAddressBytes();
long addr = (long)BitConverter.ToInt32(bytes, 0);
return new System.Net.IPAddress(addr).ToString();
}
catch (Exception e) { return e.Message; }
}
else return String.Empty;
}
//Benutzung
long longFromIP = IPToLong("127.0.0.1"); // ergibt 2130706433
string ipFromLong = LongToIP(longFromIP); // ergibt 127.0.0.1
Kommentare zum Snippet