问题描述
假设我想向我的子网中的每个主机发送一条 udp 消息(然后从我的子网中的任何主机接收一条 udp 消息):
Let's say that I want to send an udp message to every host in my subnet (and then receive an udp message from any host in my subnet):
我现在这样做:
IPAddress broadcast = IPAddress.Parse("192.168.1.255");
但我当然希望在子网不同于 192.168.1/24 的情况下动态地完成此操作.我试过了:
but of course I want this to be done dinamically in the event that the subnet is different from 192.168.1/24. I've tried with:
IPAddress broadcast = IPAddress.Broadcast;
但 IPAddress.Broadcast 代表255.255.255.255",不能用于发送消息(它会引发异常)...所以:
but IPAddress.Broadcast represents "255.255.255.255" which can't be used to send messages (it throws an exception)...so:
如何获取本地网络适配器广播地址(当然也包括网络掩码)?
how do I get the local network adapter broadcast address (or netmask of course)?
这是我想出的最终解决方案
public IPAddress getBroadcastIP()
{
IPAddress maskIP = getHostMask();
IPAddress hostIP = getHostIP();
if (maskIP==null || hostIP == null)
return null;
byte[] complementedMaskBytes = new byte[4];
byte[] broadcastIPBytes = new byte[4];
for (int i = 0; i < 4; i++)
{
complementedMaskBytes[i] = (byte) ~ (maskIP.GetAddressBytes().ElementAt(i));
broadcastIPBytes[i] = (byte) ((hostIP.GetAddressBytes().ElementAt(i))|complementedMaskBytes[i]);
}
return new IPAddress(broadcastIPBytes);
}
private IPAddress getHostMask()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in Interfaces)
{
IPAddress hostIP = getHostIP();
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
if (UnicatIPInfo.Address.ToString() == hostIP.ToString())
{
return UnicatIPInfo.IPv4Mask;
}
}
}
return null;
}
private IPAddress getHostIP()
{
foreach (IPAddress ip in (Dns.GetHostEntry(Dns.GetHostName())).AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip;
}
return null;
}
推荐答案
如果得到本地IP和子网,计算应该没问题.
If you get the local IP and subnet, it should be no problem to calculate.
可能是这样的吗?
using System;
using System.Net.NetworkInformation;
public class test
{
public static void Main()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface Interface in Interfaces)
{
if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
if (Interface.OperationalStatus != OperationalStatus.Up) continue;
Console.WriteLine(Interface.Description);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
Console.WriteLine(" IP Address is {0}", UnicatIPInfo.Address);
Console.WriteLine(" Subnet Mask is {0}", UnicatIPInfo.IPv4Mask);
}
}
}
}
给出IP地址和网络掩码时如何计算IP范围?应该给你剩下的.
这篇关于您如何获取默认网络适配器的主机广播地址?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!