簡體   English   中英

在C#中,我有一個子網位,需要創建一個子網掩碼。 我該怎么辦?

[英]In C#, I have a subnet bits and need to create a Subnet Mask. How might I do this?

我有一個任務要用C#完成。 我有一個子網名稱:192.168.10.0/24

我需要找到子網掩碼,在本例中為255.255.255.0。

但是,我需要能夠在C#中做到這一點,而無需使用System.Net庫(我正在編程的系統無法訪問此庫)。

似乎該過程應該是這樣的:

1)將子網名稱分為數字和位數。

2)將位推入我在SO上發現的位置(感謝將子網掩碼“ /”表示法轉換為Cisco 0.0.0.0標准 ):

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#知識來幫助您?

您可以使用以下方法替換該方法:

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

這是獲取蒙版的更簡單方法:

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

您不需要Net程序集以正確的順序獲取字節,可以使用BitConverter類:

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

暫無
暫無

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

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