How do you get the default broadcast address of the network adapter host? FROM#

Let's say that I want to send an udp message to every host on my subnet (and then get an udp message from any host on my subnet):

Currently:

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

but of course I want this to be done dynamically if the subnet is different from 192.168.1 / 24. I tried with:

 IPAddress broadcast = IPAddress.Broadcast; 

but IPAddress.Broadcast represents "255.255.255.255" which cannot be used to send messages (it throws an exception) ... like this:

How to get the broadcast address of the local network adapter (or, of course, the network mask)?

THIS FINAL DECISION I TAKE WITH

 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; } 
+7
c # udp networking broadcast mask
source share
1 answer

If you get the local IP address and subnet, there should be no problem calculating.

Something like this maybe?

 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 IP range when IP address and netmask are set? Should give you the rest.

+5
source share

All Articles