converting IP to byte/convert back to string

11,944

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(); 
Share:
11,944
Alexandre
Author by

Alexandre

Updated on June 17, 2022

Comments

  • Alexandre
    Alexandre almost 2 years

    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?

  • Alexandre
    Alexandre over 11 years
    Actually if i return the byte array from the database i deffinitly should follow your guideline to dont use the raw hex itself but the byte[]. Thanks!