Conversion of IPv4 address to integer in C#
Question:
How to efficiently convert an IPv4 address to an integer in C#? Additionally, please provide a method to perform the reverse transformation.
Answer:
In C#, IPv4 addresses are essentially represented as 32-bit unsigned integers. So, technically, no explicit conversion is required. However, to get the underlying integer value you can use the following steps:
For example, to convert the IPv4 address "64.233.187.99" to an integer, you would use the following code:
<code class="language-csharp">long intValue = (long)(uint)IPAddress.NetworkToHostOrder( (int)IPAddress.Parse("64.233.187.99").Address);</code>
Similarly, to convert an integer back to an IPv4 address, you can use the following steps:
For example, to convert the integer 1089059683 back to an IPv4 address, you would use the following code:
<code class="language-csharp">string addressString = IPAddress.Parse(1089059683.ToString()).ToString(); // 注意这里需要将整数转换为字符串再进行解析 ``` 或者更简洁的写法: ```csharp string addressString = new IPAddress(1089059683).ToString(); // 直接使用IPAddress构造函数</code>
Please note that in the second piece of code, the IPAddress object is constructed directly using integers as parameters without explicit conversion to strings. Both methods can achieve the goal, and the second method is more concise and efficient.
The above is the detailed content of How to Efficiently Convert IPv4 Addresses to Integers and Vice Versa in C#?. For more information, please follow other related articles on the PHP Chinese website!