I have a task to complete in C#. I have a Subnet Name: 192.168.10.0/24
I need to find the subnet mask, which would be, in this case, 255.255.255.0.
However, I need to be able to do this in C# WITHOUT the use of the System.Net library (the system I am programming in does not have access to this library).
It seems like the process should be something like:
1) Split the Subnet Name into Number and Bits.
2) Shove the Bits into this that I have found on SO (thanks to 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);
However, the problem that I have is that I do not have access to the library that contains the IPAddress.HostToNetworkOrder command in the system that I am working. Also, my C# is pretty poor. Does anyone have the C# knowledge to help?
You could replace that method with the following:
static void ToNetworkByteOrder(ref uint n) {
if(BitConverter.IsLittleEndian) {
// need to flip it
n = (
(n << 24)
|
((n & 0xff00) << 8)
|
((n & 0xff0000) >> 8)
|
(n >> 24)
);
}
}
Here's a simpler way to get the mask:
int mask = -1 << (32 - cidr);
You don't need the Net
assembly to get the bytes in the right order, you can use the BitConverter
class:
if (BitConverter.IsLittleEndian) {
byte[] parts = BitConverter.GetBytes(mask);
Array.Reverse(parts);
mask = BitConverter.ToInt32(parts, 0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.