我已经搜查SO寻求帮助,但could'nt找到一个回答我的问题。
情况:我需要一个/ NN子网掩码符号(认为iptables的)转换为0.0.0.0思科表示法
NN是1的数量在子网掩码,从最低字节到较高。每个字节为8位整数。
可能的解决方法:
请32个0的数组和填补最后NN数字为1,则组中4个字节和转换为int ...一个/ 23掩码应该是这样0.0.1.255。
我的问题是如何做到这一点的。NET ...我从来没有使用二进制处理和转换。
你们可以帮助我解决呢?
更新 - 斯蒂芬具有正确回答
下面是code移植到.NET
如果(p.LastIndexOf(/)℃的)回报磷;
INT掩模= Convert.ToInt32(0+ p.Substring(p.LastIndexOf(/)+ 1,2-));
INT zeroBits = 32 - 口罩; //零比特的数目
UINT结果= uint.MaxValue; //所有的人
//移CIDR,并减一打造CIDR一位;
//然后移动离开零比特的数目。
结果&安培; =(UINT)((((ULONG)为0x1&其中;&所述;睫毛油) - 1) - ;&所述; zeroBits);
结果=〜结果;
//注意,结果是在主机顺序,所以我们不得不转换
//像这样通过一个ip地址构造函数之前
结果=(UINT)IPAddress.HostToNetworkOrder((INT)的结果);
字符串convertedMask =新的ip地址(结果)的ToString();
解决方案
我一直扔在一起的一些通用地址屏蔽例程...
下面是一个快速和肮脏的方式从 CIDR 符号转换为子网掩码:
VAR CIDR = 23; //例如,/ 23
VAR zeroBits = 32 - CIDR; //零比特的数目
VAR的结果= uint.MaxValue; //所有的人
//移CIDR,并减一打造CIDR一位;
//然后移动离开零比特的数目。
结果&安培; =(UINT)((((ULONG)为0x1&其中;&所述; CIDR) - 1) - ;&所述; zeroBits);
//注意,结果是在主机顺序,所以我们不得不转换
//像这样通过一个ip地址构造函数之前
结果=(UINT)IPAddress.HostToNetworkOrder((INT)的结果);
I've searched SO for help but could'nt find a answer to my question.
Situation: I need to convert a "/NN" subnet mask notation (think IPTABLES) to a 0.0.0.0 cisco notation.
NN are the number of "1" in the submask, from the lowest octet to the higher. Each octet are 8 bit integers.
Possible solution:
Make a array of 32 "0" and filling the last NN digits with "1", then group in 4 octets and converting to int... a /23 mask should be like 0.0.1.255.
My question is how to do it in .NET... i never used binary manipulation and conversion.
Can you guys help me with this solution?
UPDATE - Stephen has answer correctly!
Here is the code ported to .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();
解决方案
I've been meaning to throw together some general-purpose address masking routines...
Here's a quick-and-dirty way to convert from CIDR notation to a subnet mask:
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);