簡體   English   中英

如何確定子網掩碼是否對 C# 有效

[英]How do I found out if a Subnet mask is valid with C#

我需要了解如何確定提供的子網掩碼示例(255.255.192.0)是否是有效的子網掩碼,如果有效則返回 true,否則返回 false,我已經在檢查該值是否超過 255 . 錯誤的子網將是 (255.64.0.0)

它在二進制中很有意義(11111111.01000000.00000000.00000000)子網不能停止擁有1,然后再次開始擁有它們。 我目前的想法涉及使用 bitshift,但我不確定如何去做。

我沒有使用任何庫,並且不允許用於此項目

我正在使用的代碼類似於

    Console.WriteLine("Enter a subnet mask");
    input = Console.ReadLine(); //Enters example of 255.64.0.0 which is invalid

先謝謝了,有需要可以提問

你可以這樣試試:

using System;
using System.Runtime.InteropServices;

namespace Example
{
    public class Program
    {   
        [StructLayout(LayoutKind.Explicit)]
        public struct byte_array
        {
            [FieldOffset(0)]
            public byte byte0;
            [FieldOffset(1)]
            public byte byte1;
            [FieldOffset(2)]
            public byte byte2;
            [FieldOffset(3)]
            public byte byte3;

            [FieldOffset(0)]
            public UInt32 Addr;
        }
        
        public static void Main(string[] args)
        {
            byte_array b_array = new byte_array();
            int i;
            
            b_array.byte3 = 255;
            b_array.byte2 = 64;
            b_array.byte1 = 0;
            b_array.byte0 = 0;
            
            Console.WriteLine(String.Format("{0:X4}", b_array.Addr));
            
            for(i = 31; i >= 0; i--)
                if(((1 << i) & b_array.Addr) == 0)
                    break;
            for(; i >= 0; i--)
                if(((1 << i) & b_array.Addr) != 0)
                {
                    Console.WriteLine("Bad Mask!");
                    break;
                }
        }
    }
}

我尋找了一種庫方法,但找不到。 這是我只為 IPv4 地址編寫的方法;

public static bool IsValidMask(string mask)
{
    // 1) convert the address to an int32
    if (!IPAddress.TryParse(mask, out var addr))
        return false;
    var byteVal = addr.GetAddressBytes();
    if (byteVal.Length != 4)
        return false;
    var intVal = BitConverter.ToInt32(byteVal);
    intVal = IPAddress.NetworkToHostOrder(intVal);

    // A valid mask should start with ones, and end with zeros 0b111...111000...000

    // 2) XOR to flip all the bits (0b000...000111...111)
    var uintVal = (uint)intVal ^ uint.MaxValue;

    // 3) Add 1, causing all those 1's to become 0's. (0b000...001000...000)
    // An invalid address will have leading 1's that are untouched by this step. (0b101...001000...000)
    var addOne = uintVal + 1;

    // 4) AND the two values together, to detect if any leading 1's remain
    var ret = addOne & uintVal;

    return ret == 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM