我如何发现子网掩码是否对C#有效



我需要了解如何确定提供的子网掩码示例(255.255.192.0(是否是有效的子网屏蔽,如果有效则返回true,如果无效则返回false,我已经在检查该值是否超过255。错误的子网是(255.64.0.0(

它在二进制(11111111.010000000000000000000000(中很有意义。子网不能停止具有1,然后再开始具有1。我目前的想法是使用比特移位,但不确定如何做到

我没有使用任何libaries,也不允许用于这个项目

我使用的代码有点像

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

提前感谢,如有需要可提问

我找了一个库方法,但找不到。以下是我如何只为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;
}

您可以尝试以下方式:

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;
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新