gpt4 book ai didi

c# - 如何获取默认网络适配器的主机广播地址? C#

转载 作者:太空狗 更新时间:2023-10-29 20:24:20 24 4
gpt4 key购买 nike

假设我想向我子网中的每个主机发送一个 udp 消息(然后从我子网中的任何主机接收一个 udp 消息):

目前我这样做:

IPAddress broadcast = IPAddress.Parse("192.168.1.255");

但我当然希望在子网不同于 192.168.1/24 的情况下动态完成此操作。我试过:

IPAddress broadcast = IPAddress.Broadcast;

但是 IPAddress.Broadcast 表示不能用于发送消息的“255.255.255.255”(它会抛出异常)...所以:

如何获取本地网络适配器广播地址(当然是网络掩码)?

这是我想出的最终解决方案

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和子网,计算应该没问题。

也许是这样的?

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("\tIP Address is {0}", UnicatIPInfo.Address);
Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
}
}
}
}

How to calculate the IP range when the IP address and the netmask is given?应该给你剩下的。

关于c# - 如何获取默认网络适配器的主机广播地址? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com