jad*_*son 1 .net cisco iptables mask subnet
我已经搜索了SO以寻求帮助,但找不到我的问题的答案。
情况:我需要将“ / NN”子网掩码表示法(认为IPTABLES)转换为0.0.0.0的cisco表示法。
NN是子掩码中从最低八位字节到较高八位字节的数字“ 1”。每个八位位组是8位整数。
可能的解决方案:
制作一个由32个“ 0”组成的数组,并用“ 1”填充最后一个NN数字,然后分组4个八位字节并转换为int ... / 23掩码应类似于0.0.1.255。
我的问题是如何在.NET中执行此操作...我从未使用过二进制操作和转换。
你们能帮我解决这个问题吗?
更新-斯蒂芬回答正确!
这是移植到.NET的代码
if (p.LastIndexOf("/") < 0 ) return p;
int mask= Convert.ToInt32("0"+p.Substring(p.LastIndexOf("/")+1,2));
int zeroBits = 32 - mask; // the number of zero bits
uint 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 << mascara) - 1) << zeroBits);
result = ~result;
// 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);
string convertedMask = new IPAddress(result).ToString();
Run Code Online (Sandbox Code Playgroud)
我一直想把一些通用的地址屏蔽例程放在一起。
这是一种从CIDR表示法转换为子网掩码的快捷方法:
var cidr = 23; // e.g., "/23"
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);
Run Code Online (Sandbox Code Playgroud)