Convert IP to Byte / Convert Back to String

I save the IPV4 address in the SQLSERVER 2008 database as binary (4). So, I convert the values ​​before entering data (and due to company limitations, I CANNOT create functions inside db, well, that is not discussed).

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 calling IpToBin, the generated data (for example, 0x59FC09F3). When I call HexToIp, ip came back in reverse, probably due to the small / large endian conversion.

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

+4
source share
2 answers

I think the real problem is that you are treating the raw form as a string; especially since it is binary(4) , you will never have to do this: just return it from db as byte[] . IpToBin great, but HexToIp should be:

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

then: the work is done. But with your existing HexToIp code HexToIp 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(); 
+6
source
  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; } 
0
source

All Articles