我已经搜索过寻求帮助,但找不到我的问题的答案。
情况:我需要将“/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();
我一直想将一些通用地址屏蔽例程放在一起......
这是一种快速而肮脏的转换方法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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)