Alexandre
Alexandre

Reputation: 415

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?

Upvotes: 6

Views: 13989

Answers (2)

Daniele
Daniele

Reputation: 236

    public List<IPAddress> SubtractTwoIpAddresses(IPAddress a, IPAddress b, bool includeLeft = true, bool includeRight = true)
    {
        List<IPAddress> rv = new List<IPAddress>();
        int ipA = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(a.ToString()).GetAddressBytes(), 0)),
            ipB = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(b.ToString()).GetAddressBytes(), 0));
        if (includeLeft)
            rv.Add(new IPAddress(BitConverter.GetBytes(Math.Min(ipA, ipB)).Reverse().ToArray()));
        for (int i = 1; i < Math.Max(ipA, ipB) - Math.Min(ipA, ipB); i++)
            rv.Add(new IPAddress(BitConverter.GetBytes(Math.Min(ipA, ipB) + i).Reverse().ToArray()));
        if (includeRight)
            rv.Add(new IPAddress(BitConverter.GetBytes(Math.Max(ipA, ipB)).Reverse().ToArray()));
        return rv;
    }

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062715

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(); 

Upvotes: 6

Related Questions