为什么IPAddress.MapToIPv4()抛出ArgumentOutOfRangeException? [英] Why does IPAddress.MapToIPv4() throw ArgumentOutOfRangeException?

查看:1284
本文介绍了为什么IPAddress.MapToIPv4()抛出ArgumentOutOfRangeException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code抛出一个ArgumentOutOfRangeException在最后一行

This code throws an ArgumentOutOfRangeException on the last line

var initAddress = IPAddress.Parse("1.65.128.190");
var ipv6Address = initAddress.MapToIPv6();
Assert.IsTrue(ipv6Address.IsIPv4MappedToIPv6);
var ipv4Address = ipv6Address.MapToIPv4();

任何人都可以解释为什么MapToIPv6()和MapToIPv4()不往返兼容?

Can anyone explain why MapToIPv6() and MapToIPv4() are not round trip compatible?

编辑:从ip地址构造,称为MapToIPv4()的异常起源

edit: The exception originates from the IPAddress constructor, called by MapToIPv4().

而且,当第一行是

var initAddress = IPAddress.Parse("1.65.128.90");

没有异常被抛出了

EDIT2:作为@Luaan转载此,我添加了标签[臭虫报告。还增加[BCL]。让我们来看看,如果任何MS人员会跟踪这些标签:)

edit2: as @Luaan reproduced this, I added the tag [bug-reporting]. Also added [bcl]. Let's see if any MS personnel tracks those tags :)

EDIT3:报道连接<一href="https://connect.microsoft.com/VisualStudio/feedback/details/871964">https://connect.microsoft.com/VisualStudio/feedback/details/871964

edit3: reported at Connect https://connect.microsoft.com/VisualStudio/feedback/details/871964

推荐答案

好吧,其实我已经验证了这一点,所以让我张贴此作为一个答案。

Ok, I've actually verified this, so let me post this as an answer.

在映射的地址回的IPv4的 ip地址类有一个错误。

The IPAddress class has an error when mapping the address back to IPv4.

据该.NET参考code,它这样做:

According to the .NET reference code, it does this:

long address = 
  (((m_Numbers[6] & 0x0000FF00) >> 8) | ((m_Numbers[6] & 0x000000FF) << 8)) |
  ((((m_Numbers[7] & 0x0000FF00) >> 8) | ((m_Numbers[7] & 0x000000FF) << 8)) << 16);

这个问题应该是很明显的人做位运算的.NET - 数字均 INT 秒。所以移动第二 USHORT m_Numbers [7] )会给出一个负值,因为最显著位 1 。这意味着所有的IPv4地址用一个字节比 127 从IPv6的映射回来的时候会产生错误。

The problem should be quite obvious to anyone doing bitwise operations in .NET - the numbers are all ints. So shifting the second ushort (m_Numbers[7]) will give a negative value, because the most significant bit is 1. This means that all IPv4 addresses that end with a byte higher than 127 will cause an error when mapping back from IPv6.

简单的解决将是这样的:

The simple fix would be this:

long address = 
 (((m_Numbers[6] & 0x0000FF00) >> 8) | ((m_Numbers[6] & 0x000000FF) << 8)) 
 |
 (
  (uint)(((m_Numbers[7] & 0x0000FF00) >> 8) | ((m_Numbers[7] & 0x000000FF) << 8))
  << 16
 );

仅仅通过铸造 INT UINT 之前做bitshift是卓有成效的。

Just by casting the int to an uint before doing the bitshift does the trick.

​​位运算可以说是相当棘手。我猜code是从C ++库什么的,此问题将不会明显。

Bitwise operations can be quite tricky when you factor in signed types. I guess the code was copied from a C++ library or something, where this issue wouldn't manifest.

这篇关于为什么IPAddress.MapToIPv4()抛出ArgumentOutOfRangeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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