在C#中,我有一个子网位,需要创建一个子网掩码。我怎么能这样做?

时间:2012-10-24 15:20:08

标签: c# cisco subnet

我有一项任务要在C#中完成。我有一个子网名称:192.168.10.0/24

我需要找到子网掩码,在本例中为255.255.255.0。

但是,我需要能够在C#中完成此操作而不使用System.Net库(我编程的系统无法访问此库)。

似乎这个过程应该是这样的:

1)将子网名称拆分为数字和位。

2)将比特推到我在SO上找到的那个(感谢Converting subnet mask "/" notation to Cisco 0.0.0.0 standard):

var cidr = 24; // e.g., "/24" 
var zeroBits = 32 - cidr; // the number of zero bits 
var result = uint.MaxValue; // all ones 

// Shift "cidr" and subtract one to create "cidr" one bits; 
//  then move them left the number of zero bits. 
result &= (uint)((((ulong)0x1 << cidr) - 1) << zeroBits); 

// Note that the result is in host order, so we'd have to convert 
//  like this before passing to an IPAddress constructor 
result = (uint)IPAddress.HostToNetworkOrder((int)result); 

但是,我遇到的问题是我无法访问我正在使用的系统中包含IPAddress.HostToNetworkOrder命令的库。另外,我的C#很差。有没有人有C#知识可以提供帮助?

2 个答案:

答案 0 :(得分:3)

您可以使用以下内容替换该方法:

static void ToNetworkByteOrder(ref uint n) {
    if(BitConverter.IsLittleEndian) {
        // need to flip it
        n = (
            (n << 24)
            |
            ((n & 0xff00) << 8)
            |
            ((n & 0xff0000) >> 8)
            |
            (n >> 24)
        );
    }
}

答案 1 :(得分:2)

这是获取面具的更简单方法:

int mask = -1 << (32 - cidr);

您不需要Net程序集以正确的顺序获取字节,您可以使用BitConverter类:

if (BitConverter.IsLittleEndian) {
  byte[] parts = BitConverter.GetBytes(mask);
  Array.Reverse(parts);
  mask = BitConverter.ToInt32(parts, 0);
}