c# c#判斷ipv6 - 如何檢查輸入IP是否屬於特定IP範圍



ip驗證 ip判斷 (7)

您可能希望通過@jsakamoto考慮此庫,它允許您解析IP地址字符串的範圍,例如“192.168.0.0/24”和“192.168.0.0/255.255.255.0”和“192.168.0.0-192.168.0.255” ,並可以檢查。 該庫支持IPv4和IPv6。

https://github.com/jsakamoto/ipaddressrange

它也可以通過NuGet安裝:

http://www.nuget.org/packages/IPAddressRange/

using NetTools;
...
// rangeA.Begin is "192.168.0.0", and rangeA.End is "192.168.0.255".
var rangeA = IPAddressRange.Parse("192.168.0.0/255.255.255.0");
rangeA.Contains(IPAddress.Parse("192.168.0.34")); // is True.
rangeA.Contains(IPAddress.Parse("192.168.10.1")); // is False.
rangeA.ToCidrString(); // is 192.168.0.0/24

// rangeB.Begin is "192.168.0.10", and rangeB.End is "192.168.10.20".
var rangeB1 = IPAddressRange.Parse("192.168.0.10 - 192.168.10.20");
rangeB1.Contains(IPAddress.Parse("192.168.3.45")); // is True.
rangeB1.Contains(IPAddress.Parse("192.168.0.9")); // is False.

// Support shortcut range description. 
// ("192.168.10.10-20" means range of begin:192.168.10.10 to end:192.168.10.20.)
var rangeB2 = IPAddressRange.Parse("192.168.10.10-20");

// Support CIDR expression and IPv6.
var rangeC = IPAddressRange.Parse("fe80::/10"); 
rangeC.Contains(IPAddress.Parse("fe80::d503:4ee:3882:c586%3")); // is True.
rangeC.Contains(IPAddress.Parse("::1")); // is False.

如果我們讓用戶輸入幾個ip範圍,例如172.16.11.5 - 100,我怎麼能寫一個函數來檢查IP(172.16.11.50)是否屬於範圍?

是否有任何現有的.NET庫可以利用?


我以前在codeproject上使用過這段代碼,這可能對你有用。

http://www.codeproject.com/KB/IP/ipnumbers.aspx

您可以向IPList添加由From IP和To IP號定義的一系列IP號。 該方法將範圍分解為標準IP範圍並查找其掩碼。 因此,範圍“10.0.0.5”到“10.0.0.20”將被分解為以下範圍並添加到列表中:10.0.0.5,10.0.0.20,10.0.0.6 / 31,10.0.0.16 / 30和10.0。 0.8 / 29,您將有可能對此進行檢查。

免責聲明:Class僅使用簡單的數據集進行測試,而Class缺乏對所提供的IP號和IP掩碼的驗證。 這應該在生產環境中使用之前修復。


public static bool IsInRange(string startIpAddr, string endIpAddr, string address)
{
    long ipStart = BitConverter.ToInt32(IPAddress.Parse(startIpAddr).GetAddressBytes().Reverse().ToArray(), 0);

    long ipEnd = BitConverter.ToInt32(IPAddress.Parse(endIpAddr).GetAddressBytes().Reverse().ToArray(), 0);

    long ip = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes().Reverse().ToArray(), 0);

    return ip >= ipStart && ip <= ipEnd; //edited
}

Console.WriteLine(IsInRange("100.0.0.1", "110.0.0.255", "102.0.0.4"));//true

框架中沒有任何內置,但創建IPAddressRange類不需要花費太多精力。

您可以通過在較低地址,較高地址和比較地址上調用IPAddress.GetAddressBytes來比較範圍。 從第一個字節開始,檢查比較地址是否在上/下地址範圍內。

此方法適用於IPv4和IPv6地址。

public class IPAddressRange
{
    readonly AddressFamily addressFamily;
    readonly byte[] lowerBytes;
    readonly byte[] upperBytes;

    public IPAddressRange(IPAddress lowerInclusive, IPAddress upperInclusive)
    {
        // Assert that lower.AddressFamily == upper.AddressFamily

        this.addressFamily = lowerInclusive.AddressFamily;
        this.lowerBytes = lowerInclusive.GetAddressBytes();
        this.upperBytes = upperInclusive.GetAddressBytes();
    }

    public bool IsInRange(IPAddress address)
    {
        if (address.AddressFamily != addressFamily)
        {
            return false;
        }

        byte[] addressBytes = address.GetAddressBytes();

        bool lowerBoundary = true, upperBoundary = true;

        for (int i = 0; i < this.lowerBytes.Length && 
            (lowerBoundary || upperBoundary); i++)
        {
            if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) ||
                (upperBoundary && addressBytes[i] > upperBytes[i]))
            {
                return false;
            }

            lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
            upperBoundary &= (addressBytes[i] == upperBytes[i]);
        }

        return true;
    }
}

注意:上面的代碼可以擴展為添加公共靜態工廠方法FromCidr(IPAddress address, int bits)



最好是將這些地址轉換為整數,然後執行比較。

示例來自: IP到整數

要將IP地址轉換為整數,請將其分為四個八位字節。 例如,您提供的IP地址可以分為:

First Octet:    217
Second Octet:   110
Third Octet:    18
Fourth Octet:   206

要從虛線字符串計算小數地址,請執行以下計算。

    (first octet * 256³) + (second octet * 256²) + (third octet * 256) + (fourth octet)
=   (first octet * 16777216) + (second octet * 65536) + (third octet * 256) + (fourth octet)
=   (217 * 16777216) + (110 * 65536) + (18 * 256) + (206)
=   3647869646

考慮到IPv6,您可以將它們轉換為整數(128位與32位IPv4)。 看看這個問題:將IPv6格式化為C#中的int並將其存儲在SQL Server中

最簡單的方法是讓框架為您完成此操作。 使用IPAddress.Parse解析地址,然後使用IPAddress.Parse將“number”作為byte[]


What can you do about it?

There is a lot of good answers here explaining what a null reference is and how to debug it. But there is very little on how to prevent the issue or at least make it easier to catch.

Check arguments

For example, methods can check the different arguments to see if they are null and throw an ArgumentNullException , an exception obviously created for this exact purpose.

The constructor for the ArgumentNullException even takes the name of the parameter and a message as arguments so you can tell the developer exactly what the problem is.

public void DoSomething(MyObject obj) {
    if(obj == null) 
    {
        throw new ArgumentNullException("obj", "Need a reference to obj.");
    }
}

Use Tools

There are also several libraries that can help. "Resharper" for example can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute

There's "Microsoft Code Contracts" where you use syntax like Contract.Requires(obj != null) which gives you runtime and compile checking: Introducing Code Contracts .

There's also "PostSharp" which will allow you to just use attributes like this:

public void DoSometing([NotNull] obj)

By doing that and making PostSharp part of your build process obj will be checked for null at runtime. See: PostSharp null check

Plain Code Solution

Or you can always code your own approach using plain old code. For example here is a struct that you can use to catch null references. It's modeled after the same concept as Nullable<T> :

[System.Diagnostics.DebuggerNonUserCode]
public struct NotNull<T> where T: class
{
    private T _value;

    public T Value
    {
        get
        {
            if (_value == null)
            {
                throw new Exception("null value not allowed");
            }

            return _value;
        }
        set
        {
            if (value == null)
            {
                throw new Exception("null value not allowed.");
            }

            _value = value;
        }
    }

    public static implicit operator T(NotNull<T> notNullValue)
    {
        return notNullValue.Value;
    }

    public static implicit operator NotNull<T>(T value)
    {
        return new NotNull<T> { Value = value };
    }
}

You would use very similar to the same way you would use Nullable<T> , except with the goal of accomplishing exactly the opposite - to not allow null . 這裡有些例子:

NotNull<Person> person = null; // throws exception
NotNull<Person> person = new Person(); // OK
NotNull<Person> person = GetPerson(); // throws exception if GetPerson() returns null

NotNull<T> is implicitly cast to and from T so you can use it just about anywhere you need it. For example, you can pass a Person object to a method that takes a NotNull<Person> :

Person person = new Person { Name = "John" };
WriteName(person);

public static void WriteName(NotNull<Person> person)
{
    Console.WriteLine(person.Value.Name);
}

As you can see above as with nullable you would access the underlying value through the Value property. Alternatively, you can use an explicit or implicit cast, you can see an example with the return value below:

Person person = GetPerson();

public static NotNull<Person> GetPerson()
{
    return new Person { Name = "John" };
}

Or you can even use it when the method just returns T (in this case Person ) by doing a cast. For example, the following code would just like the code above:

Person person = (NotNull<Person>)GetPerson();

public static Person GetPerson()
{
    return new Person { Name = "John" };
}

Combine with Extension

Combine NotNull<T> with an extension method and you can cover even more situations. Here is an example of what the extension method can look like:

[System.Diagnostics.DebuggerNonUserCode]
public static class NotNullExtension
{
    public static T NotNull<T>(this T @this) where T: class
    {
        if (@this == null)
        {
            throw new Exception("null value not allowed");
        }

        return @this;
    }
}

And here is an example of how it could be used:

var person = GetPerson().NotNull();

GitHub上

For your reference I made the code above available on GitHub, you can find it at:

https://github.com/luisperezphd/NotNull

Related Language Feature

C# 6.0 introduced the "null-conditional operator" that helps with this a little. With this feature, you can reference nested objects and if any one of them is null the whole expression returns null .

This reduces the number of null checks you have to do in some cases. The syntax is to put a question mark before each dot. Take the following code for example:

var address = country?.State?.County?.City;

Imagine that country is an object of type Country that has a property called State and so on. If country , State , County , or City is null then address will be null . Therefore you only have to check whether address is null`.

It's a great feature, but it gives you less information. It doesn't make it obvious which of the 4 is null.

Built-in like Nullable?

C# has a nice shorthand for Nullable<T> , you can make something nullable by putting a question mark after the type like so int?

It would be nice if C# had something like the NotNull<T> struct above and had a similar shorthand, maybe the exclamation point (!) so that you could write something like: public void WriteName(Person! person) .





c# asp.net