使用.NET测试IP地址是否在地址范围内 [英] Testing if an IP address is within a range of addresses with .NET

查看:104
本文介绍了使用.NET测试IP地址是否在地址范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET是否具有IP地址范围的概念?

Does .NET have the notion of IP Address Ranges?

我需要测试给定的IP地址是否在地址范围内.

I need to test if a given IP address is within a range of addresses.

我可以编写一些API来给我类似

I could write some API that would give me something like

IPRange ipRange = IPRange.Parse("127.0.0.1-127.0.0.15");
ipRange.Contains(someAddress);

但是如果已经内置了类似的功能,我不想重新发明轮子.

but I don't want to reinvent the wheel if there is already similar functionality built in.

推荐答案

否,但这是可以完成的操作(VB,因为代码标签未包含在OP中)

No, but here is how it can be done (VB since code tag not included in OP)

'test values
Dim rangeStart As Net.IPAddress = Net.IPAddress.Parse("192.168.133.1")
Dim rangeEnd As Net.IPAddress = Net.IPAddress.Parse("192.168.133.254")
Dim check As Net.IPAddress = Net.IPAddress.Parse("192.168.133.230")

'get the bytes of the address
Dim rbs() As Byte = rangeStart.GetAddressBytes
Dim rbe() As Byte = rangeEnd.GetAddressBytes
Dim cb() As Byte = check.GetAddressBytes

'reverse them for conversion
Array.Reverse(rbs)
Array.Reverse(rbe)
Array.Reverse(cb)

'convert them
Dim rs As UInt32 = BitConverter.ToUInt32(rbs, 0)
Dim re As UInt32 = BitConverter.ToUInt32(rbe, 0)
Dim chk As UInt32 = BitConverter.ToUInt32(cb, 0)

'check
If chk >= rs AndAlso chk <= re Then
    Debug.WriteLine("In Range")
Else
    Debug.WriteLine("Not In Range")
End If

这篇关于使用.NET测试IP地址是否在地址范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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