如何在 C# 中将 IPv4 地址转换为整数?

7

本文介绍了如何在 C# 中将 IPv4 地址转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在寻找将标准 IPv4 地址转换为整数的函数.可用于执行相反操作的功能的奖励积分.

I'm looking for a function that will convert a standard IPv4 address into an Integer. Bonus points available for a function that will do the opposite.

解决方案应该在 C# 中.

Solution should be in C#.

推荐答案

32 位无符号整数 IPv4 地址.同时,IPAddress.Address 属性虽然已弃用,但它是一个 Int64,它返回 IPv4 地址的无符号 32 位值(问题是,它是按网络字节顺序排列的,因此您需要交换它周围).

32-bit unsigned integers are IPv4 addresses. Meanwhile, the IPAddress.Address property, while deprecated, is an Int64 that returns the unsigned 32-bit value of the IPv4 address (the catch is, it's in network byte order, so you need to swap it around).

例如,我的本地 google.com 位于 64.233.187.99.这相当于:

For example, my local google.com is at 64.233.187.99. That's equivalent to:

64*2^24 + 233*2^16 + 187*2^8 + 99
= 1089059683

确实,http://1089059683/ 按预期工作(至少在 Windows 中,用 IE、Firefox 和 Chrome 测试;但在 iPhone 上不工作).

And indeed, http://1089059683/ works as expected (at least in Windows, tested with IE, Firefox and Chrome; doesn't work on iPhone though).

这是一个显示两种转换的测试程序,包括网络/主机字节交换:

Here's a test program to show both conversions, including the network/host byte swapping:

using System;
using System.Net;

class App
{
    static long ToInt(string addr)
    {
        // careful of sign extension: convert to uint first;
        // unsigned NetworkToHostOrder ought to be provided.
        return (long) (uint) IPAddress.NetworkToHostOrder(
             (int) IPAddress.Parse(addr).Address);
    }

    static string ToAddr(long address)
    {
        return IPAddress.Parse(address.ToString()).ToString();
        // This also works:
        // return new IPAddress((uint) IPAddress.HostToNetworkOrder(
        //    (int) address)).ToString();
    }

    static void Main()
    {
        Console.WriteLine(ToInt("64.233.187.99"));
        Console.WriteLine(ToAddr(1089059683));
    }
}

这篇关于如何在 C# 中将 IPv4 地址转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14