How to convert an IPv4 address into a integer in C#?(如何在 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 地址转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中将 IPv4 地址转换为整数?


- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01