简体   繁体   中英

c# Is there a simpler solution for hex2ip

I want convert a hex C0A8B825 ipV4 to a readable ip address 192.168.184.37 . I am looking for a better solution.

My current solution:

var ipAddress = GetIpAddress("C0A8B825"); //192.168.184.37

public static string GetIpAddress(string hex)
{
    var ipPart1 = int.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
    var ipPart2 = int.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
    var ipPart3 = int.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
    var ipPart4 = int.Parse(hex.Substring(6, 2), NumberStyles.HexNumber);
    return $"{ipPart1}.{ipPart2}.{ipPart3}.{ipPart4}";
}

If you only ever deal with IPv4, you could use:

// This will convert to a 32 bit integer representation of the ip
int ip = Convert.ToInt32("C0A8B825", 16);
// IPAddress CTOR needs BigEndian / "Network Byte Order"
if( BitConverter.IsLittleEndian) ip = IPAddress.HostToNetworkOrder(ip); 
var result = new IPAddress(ip).ToString(); // Will autoformat into the desired string.

contents of result:

192.168.184.37

I'll see if I can add a Solution for both IPv4 and IPv6 later on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM