如何动态获取本地 IP 广播地址 C#

chr*_*ris 1 c# network-programming broadcast

我的第一个问题是,C# UDP Chat 没有收到消息,试图解决这个问题是为了避免。

IPAddress.Broadcast
Run Code Online (Sandbox Code Playgroud)

所以我写了一个函数来确定本地广播:

    private IPAddress get_broadcast()
    {
        try
        {
            string ipadress;
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); // get a list of all local IPs
            IPAddress localIpAddress = ipHostInfo.AddressList[0]; // choose the first of the list
            ipadress = Convert.ToString(localIpAddress); // convert to string
            ipadress = ipadress.Substring(0, ipadress.LastIndexOf(".")+1); // cuts of the last octet of the given IP 
            ipadress += "255"; // adds 255 witch represents the local broadcast
            return IPAddress.Parse(ipadress); 
        }
        catch (Exception e)
        {
            errorHandler(e);
            return IPAddress.Parse("127.0.0.1");// in case of error return the local loopback
        }
    }
Run Code Online (Sandbox Code Playgroud)

但这仅适用于 /24 网络我经常在 /24(在家)和 /16(在工作)网络之间切换。所以硬编码的子网掩码不符合我的要求。

那么,有没有什么好的方法可以在不使用“IPAddress.Broadcast”的情况下确定本地广播?

nb.*_*iev 6

我知道这很旧,但我不喜欢循环,所以这里还有一个解决方案:

    public static IPAddress GetBroadcastAddress(UnicastIPAddressInformation unicastAddress)
    {
       return GetBroadcastAddress(unicastAddress.Address, unicastAddress.IPv4Mask);
    }

    public static IPAddress GetBroadcastAddress(IPAddress address, IPAddress mask)
    {
        uint ipAddress = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
        uint ipMaskV4 = BitConverter.ToUInt32(mask.GetAddressBytes(), 0);
        uint broadCastIpAddress = ipAddress | ~ipMaskV4;

        return new IPAddress(BitConverter.GetBytes(broadCastIpAddress));
    }
Run Code Online (Sandbox Code Playgroud)


Fla*_*ric 5

public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
{
  byte[] ipAdressBytes = address.GetAddressBytes();
  byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

  if (ipAdressBytes.Length != subnetMaskBytes.Length)
    throw new ArgumentException("Lengths of IP address and subnet mask do not match.");

  byte[] broadcastAddress = new byte[ipAdressBytes.Length];
  for (int i = 0; i < broadcastAddress.Length; i++)
  {
    broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
  }
  return new IPAddress(broadcastAddress);
}
Run Code Online (Sandbox Code Playgroud)

从这里获取的解决方案:http://blogs.msdn.com/b/knom/archive/2008/12/31/ip-address-calculations-with-c-subnetmasks-networks.aspx