title: How do you get host's broadcast address of the default network adapter? C#
body: <p>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):</p>
  
  <p>at the moment I do:</p>
  
  <pre><code>IPAddress broadcast = IPAddress.Parse("192.168.1.255");
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>IPAddress broadcast = IPAddress.Broadcast;
  </code></pre>
  
  <p>but IPAddress.Broadcast represents "255.255.255.255" which can't be used to send messages (it throws an exception)...so:</p>
  
  <p>how do I get the local network adapter broadcast address (or netmask of course)?</p>
  
  <p><strong>THIS IS THE FINAL SOLUTION I CAME UP WITH</strong></p>
  
  <pre><code>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 &lt; 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;
  }
  </code></pre>