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; }
c # udp networking broadcast mask
Carlo arnaboldi
source share