如何确定我的计算机的 IP 地址是否属于指定的网络地址?
string myHost = System.Net.Dns.GetHostName();
string myIP =
System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
MessageBox.Show(myIP);
TextReader read = new StreamReader(//Text file with network address);
var ip = read.ReadLine();
read.Close();
if (ip == //Need help with this part)
MessageBox.Show("You are on the network");
else
MessageBox.Show("You are not on the network");
我可以获得我的计算机地址,但我需要将其与网络地址进行比较,如果它属于该网络地址,则表明它属于该网络地址。
string myHost = System.Net.Dns.GetHostName();
string myIP =
System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();
MessageBox.Show(myIP);
TextReader read = new StreamReader(//Text file with network address);
var ip = read.ReadLine();
read.Close();
if (ip == //Need help with this part)
MessageBox.Show("You are on the network");
else
MessageBox.Show("You are not on the network");
I can get my computers address but I need to compare it to a network address and if it falls under that network address to show that it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的程序在 IP 无效时崩溃,您可以将其更改为检查该异常的 try catch(运行它并使其崩溃以查找异常)。这就是我在与 Lidgren 的多人游戏中验证 IP 的方法。
尽管这可能不是最好的方法,但它确实有效。
If your program crashes when your IP is invalid, you can change it over to a try catch that checks for that exception (run it and crash it to find the exception). This is how I validated the IP in my multiplayer with Lidgren.
Though this is probably not the best way, it works.
查看 ip 是否在某个范围内的一种简单方法是将 ip 以及范围的开头和结尾转换为 long(可以编写一个函数以将 IP 地址转换为 long)。然后查看ip是否在两个数字之间。
例如:
要检查的IP:172.17.1.25 -- 转换为long --> 172017001025
范围:
Start - 172.0.0.0 -- 转换为 long --> 172000000000
End - 172.255.255.255 -- 转换为 long --> 172255255255
现在只需检查 ip 是否在开始值和结束值之间。
One simple way to see if an ip is in a range is to convert the ip and the start and end of the range to longs (a function can be written for the conversion to a long from an IP address). Then see if the ip is between the two numbers.
For example:
IP to check: 172.17.1.25 -- Converted to long --> 172017001025
Range:
Start - 172.0.0.0 -- Converted to long --> 172000000000
End - 172.255.255.255 -- Converted to long --> 172255255255
Now just check if the ip is between the start and end values.
我推荐可以在 codeplex 上找到的 IPNetwork 实用程序。它非常灵活且功能强大。它将允许您做很多事情,确定给定 IP 地址的网络就是其中之一。
http://ipnetwork.codeplex.com/
代码应如下所示:
I recommend the IPNetwork utility that can be found on codeplex. It is pretty flexible and powerful. It will allow you to do a lot of things, and determining the network for a given ip address is one of them.
http://ipnetwork.codeplex.com/
The code should look like :