Reputation: 57
My first Problem was, C# UDP Chat receive no message, one atempt to fix this was to avoid.
IPAddress.Broadcast
So i wrote a function to determine the local 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
}
}
but this only works on /24 Networks I often switch between /24(at home) and /16(at work) networks. So a hard coded subnetmask don't fit my requirements.
so, is there any good way to determine the local broadcast without using "IPAddress.Broadcast"?
Upvotes: 2
Views: 11838
Reputation: 389
I know this is old, but I didn't like the loop, so here is one more solution:
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));
}
Upvotes: 9
Reputation: 21
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);
}
Upvotes: 2
Reputation: 8111
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);
}
Solution taken from here: http://blogs.msdn.com/b/knom/archive/2008/12/31/ip-address-calculations-with-c-subnetmasks-networks.aspx
Upvotes: 5