简体   繁体   English

如何在C#/ asp.net中将IP地址拼接为网络地址?

[英]How to splice IP address into network address in C# / asp.net?

I'm working on a service desk application that returns a variety of information on the local network of a PC. 我正在开发一个服务台应用程序,该应用程序可以在PC的本地网络上返回各种信息。

What I want to do is take the ip address of the PC - say 10.20.30.1 / 24, and get just the network octets. 我要执行的操作是获取PC的IP地址-例如10.20.30.1 / 24,并仅获取网络八位字节。 10.20.30 in this case. 在这种情况下为10.20.30。 However, even if the network was something like 100.15.1 it would still need to work. 但是,即使网络类似于100.15.1,它仍然需要工作。

I'd then want to add on different device numbers. 然后,我想添加其他设备号。 For instance, if all the switches in a network fall in the 230 - 235 range by policy, I'd want to be able to cycle through and ping those numbers looking for active switches. 例如,如果根据策略,网络中的所有交换机都落在230-235范围内,那么我希望能够循环切换并ping这些数字以查找活动的交换机。

Right now I'm only working with /24 networks. 目前,我仅使用/ 24网络。

So far I'm pulling the IP address of the PCs fine, but I'm a little lost on how to proceed.. Should I change the IP into a string and use some kind of regex method to strip the first three octets? 到目前为止,我已经很好地提取了PC的IP地址,但是我对如何进行操作有些迷茫。我应该将IP更改为字符串并使用某种正则表达式方法来剥离前三个八位字节吗? That feels a little clunky. 感觉有点笨拙。

I don't mind reading up on new methods, etc, I'm just looking to get pointed in the right direction, so to speak. 我不介意阅读新方法等,我只是想指出正确的方向,可以这么说。

Just 只是

var s = "10.20.30.1 / 24";
s = s.Substring(0, s.LastIndexOf(".")); //"10.20.30"

You should use the IPNetwork2 nuget package that parse ipnetworks. 您应该使用解析ipnetworks的IPNetwork2 nuget包。

https://www.nuget.org/packages/IPNetwork2/ https://www.nuget.org/packages/IPNetwork2/

https://github.com/lduchosal/ipnetwork https://github.com/lduchosal/ipnetwork

IPNetwork ipnetwork = IPNetwork.Parse("10.20.30.1/24");

Console.WriteLine("Network : {0}", ipnetwork.Network);

Output 输出量

Network : 10.20.30.0

Have fun ! 玩得开心 !

Regex methods wont work unless the network addresses are at 8-bit multiples. 除非网络地址是8位的倍数,否则正则表达式方法将不起作用。 For a network address of abcd/n, what you need to do is create a bit-mask with n-ones, and then bitwise-and it to the IP address you want to test. 对于abcd / n的网络地址,您需要做的是创建一个带有n个1的位掩码,然后按位进行连接,然后将其设置为要测试的IP地址。

So mask = 0xffffffff << (32-n) to get you the bitmask, and then IPAddress_as_uint && mask to get you the network portion. 因此, mask = 0xffffffff << (32-n)为您提供位掩码,然后为IPAddress_as_uint && mask获得网络部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM