如何在 C# 中将 IPv4 地址转换为整数? [英] How to convert an IPv4 address into a integer in C#?

查看:46
本文介绍了如何在 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 地址转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆