csharp Ip范围在C#
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Ip范围在C#相关的知识,希望对你有一定的参考价值。
using System;
using System.Net;
namespace Example.Net
{
/// <summary>
/// Represents a range of Ip Addresses
/// </summary>
public class IpRange
{
/// <summary>
/// Holds starting Ip Address as a string
/// </summary>
private String _start;
/// <summary>
/// Holds ending Ip Address as a string
/// </summary>
private String _end;
/// <summary>
/// Starting Ip Address
/// </summary>
public IPAddress StartAddress;
/// <summary>
/// Ending Ip Address
/// </summary>
public IPAddress EndAddress;
/// <summary>
/// Starting address in byte form
/// </summary>
private byte[] StartBytes;
/// <summary>
/// Ending address in byte form
/// </summary>
private byte[] EndBytes;
/// <summary>
/// Name of the range
/// </summary>
/// <remarks>
/// Default value is "Unnamed"
/// </remarks>
public String RangeName = "Unnamed";
/// <summary>
/// Starting Address
/// </summary>
public String Start
{
get
{
return _start;
}
set
{
_start = value;
StartAddress = IPAddress.Parse(value);
StartBytes = StartAddress.GetAddressBytes();
}
}
/// <summary>
/// Ending Address
/// </summary>
public String End
{
get
{
return _end;
}
set
{
_end = value;
EndAddress = IPAddress.Parse(value);
EndBytes = EndAddress.GetAddressBytes();
}
}
/// <summary>
/// Checks if an IP Address falls in the range
/// </summary>
/// <param name="ipAddress"></param>
/// <returns></returns>
public bool InRange(String ipAddress)
{
IPAddress address;
if (IPAddress.TryParse(ipAddress, out address))
{
return InRange(address);
}
return false;
}
/// <summary>
/// Checks if an IP Address falls in the range
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
/// <remarks>
/// http://stackoverflow.com/a/2138724
/// Richard Szalay
/// </remarks>
public bool InRange(IPAddress address)
{
if(address.AddressFamily != StartAddress.AddressFamily
|| address.AddressFamily != EndAddress.AddressFamily)
{
return false;
}
var addressBytes = address.GetAddressBytes();
bool lowerBoundary = true;
bool upperBoundary = true;
for (int i = 0; (i < StartBytes.Length) && (lowerBoundary || upperBoundary); i++)
{
if ((lowerBoundary && addressBytes[i] < StartBytes[i]) ||
(upperBoundary && addressBytes[i] > EndBytes[i]))
{
return false;
}
lowerBoundary &= (addressBytes[i] == StartBytes[i]);
upperBoundary &= (addressBytes[i] == EndBytes[i]);
}
return true;
}
}
}
以上是关于csharp Ip范围在C#的主要内容,如果未能解决你的问题,请参考以下文章
csharp C#中的密码安全随机数(范围:0到4,294,967,295)
csharp 检查区间或范围[N ... M]中的素数。从C#http://www.introprogramming.info/wp-c的计算机编程基础知识
csharp 检查区间或范围[N ... M]中的素数。从C#http://www.introprogramming.info/wp-c的计算机编程基础知识