Home > Backend Development > C++ > How to Convert IPv4 Addresses to Integers and Vice Versa in C#?

How to Convert IPv4 Addresses to Integers and Vice Versa in C#?

Susan Sarandon
Release: 2025-01-08 13:42:41
Original
705 people have browsed it

How to Convert IPv4 Addresses to Integers and Vice Versa in C#?

Conversion between IPv4 address and integer in C#

When dealing with IPv4 addresses, it is often necessary to convert them to integers or vice versa. C# provides several methods to perform these conversions.

To convert an IPv4 address to an integer, you can use the IPAddress attribute of the class, which returns a 32-bit unsigned integer representing the IPv4 address. However, this property returns the address in network byte order, so the bytes need to be swapped to get host byte order. Address

For example, to convert the IP address "64.233.187.99" to an integer:

<code class="language-csharp">long address = (long)(uint)IPAddress.NetworkToHostOrder(
    (int)IPAddress.Parse("64.233.187.99").Address);</code>
Copy after login
To convert an integer back to an IPv4 address, you can use the constructor of the

class: IPAddress

<code class="language-csharp">string ipAddress = new IPAddress((uint)IPAddress.HostToNetworkOrder(
    (int)address)).ToString();</code>
Copy after login
Here is a complete example program demonstrating both conversions:

The above is the detailed content of How to Convert IPv4 Addresses to Integers and Vice Versa 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