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 地址转换为整数?
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
