Conversion between IPv4 address and integer in C#
C# provides efficient built-in functions for converting between standard IPv4 addresses and integers. A 32-bit unsigned integer can represent an IPv4 address.
To convert an IPv4 address to an integer, you can use the ToInt
method provided in the following sample code:
<code class="language-csharp">public static long ToInt(string addr) { // 确保正确处理符号扩展 return (long)(uint)IPAddress.NetworkToHostOrder( (int)IPAddress.Parse(addr).Address); }</code>
Reverse conversion, that is, converting the integer back to an IPv4 address, can use the ToAddr
method:
<code class="language-csharp">public static string ToAddr(long address) { return IPAddress.Parse(address.ToString()).ToString(); }</code>
These methods demonstrate the conversion process, including handling network/host byte swapping. The NetworkToHostOrder
function is essential to ensure accurate conversion between network byte order (used when transmitting over the network) and host byte order (used on the machine).
The above is the detailed content of How Can I Convert IPv4 Addresses to and from Integers in C#?. For more information, please follow other related articles on the PHP Chinese website!