Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting IP to byte/convert back to string

I'm storing an IPV4 address on a SQLSERVER 2008 database as Binary(4). So, I'm converting the values before data input (and due to company restrictions I CANNOT create functions inside the db, well thats not up for discussion).

public static byte[] IpToBin(string ip)
{
    return IPAddress.Parse(ip).GetAddressBytes();
}

public static string HexToIp(string ip)
{
    return new IPAddress(long.Parse(ip, NumberStyles.HexNumber)).ToString(); 
}

After IpToBin is called, the data generated is (for example 0x59FC09F3). When I call HexToIp the ip came reversed probably due little/big endian conversion.

Could anyone please come up with a decent solution without 50 billion lines of code?

like image 950
Alexandre Avatar asked Jan 24 '13 10:01

Alexandre


1 Answers

I think the real issue here is that you are treating the raw form as a string; especially since it is binary(4), you should never have to do that: just fetch it back from the db as a byte[]. IpToBin is fine, but HexToIp should probably be:

public static IPAddress BinToIp(byte[] bin)
{
    return new IPAddress(bin);
}

then: job done. But with your existing HexToIp code, you want:

return new IPAddress(new byte[] {
    Convert.ToByte(ip.Substring(0,2), 16), Convert.ToByte(ip.Substring(2,2), 16),
    Convert.ToByte(ip.Substring(4,2), 16), Convert.ToByte(ip.Substring(6,2), 16)}
    ).ToString(); 
like image 115
Marc Gravell Avatar answered Oct 05 '22 19:10

Marc Gravell