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

时间:2014-08-13 08:08:55

标签: c# network-programming broadcast

我的第一个问题是C# UDP Chat receive no message,一个尝试解决这个问题的方法是避免。

IPAddress.Broadcast

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

    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
        }
    }

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

那么,有没有什么好方法可以在不使用" IPAddress.Broadcast"来确定本地广播?

3 个答案:

答案 0 :(得分:4)

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);
}

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

答案 1 :(得分:1)

IPAddress GetBroadCastIP(IPAddress host, IPAddress mask)
    {
        byte[] broadcastIPBytes = new byte[4];
        byte[] hostBytes = host.GetAddressBytes();
        byte[] maskBytes = mask.GetAddressBytes();
        for (int i = 0; i < 4; i++)
        {
            broadcastIPBytes[i] = (byte)(hostBytes[i] | (byte)~maskBytes[i]);
        }
        return new IPAddress(broadcastIPBytes);
    }

答案 2 :(得分:1)

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

    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));
    }