Home > Backend Development > C++ > How Can I Convert IPv4 Addresses to and from Integers in C#?

How Can I Convert IPv4 Addresses to and from Integers in C#?

Linda Hamilton
Release: 2025-01-08 13:26:41
Original
299 people have browsed it

How Can I Convert IPv4 Addresses to and from Integers in C#?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template