Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Calculating the broadcast address for a subnet

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
22 Aug 2008Public Domain 29.6K   10   3
How to calculate the broadcast address for a subnet.

Introduction

This code returns the subnet broadcast address for a given IP address and subnet mask.

I needed it for a WOL function on a website which was in a different subnet and where the standard broadcast address didn't work.

Using the code

This function is quite easy, and could be used, for example, in an UdpClient object, like this:

C#
UdpClient client = new UdpClient();
client.Connect(CalculateBroadCastAddress(ip,nm).ToString(), 40000);

Here is the complete source code:

C#
using System.Net.Sockets;
using System.Net;
using System.Globalization;
using System.Collections;

           
static IPAddress CalculateBroadCastAddress(IPAddress currentIP, IPAddress ipNetMask)
{
    string[] strCurrentIP = currentIP.ToString().Split('.');
    string[] strIPNetMask = ipNetMask.ToString().Split('.');

    ArrayList arBroadCast = new ArrayList();

    for (int i = 0; i < 4; i++)
    {
        int nrBCOct = int.Parse(strCurrentIP[i]) | (int.Parse(strIPNetMask[i]) ^ 255);
        arBroadCast.Add(nrBCOct.ToString());
    }
    return IPAddress.Parse(arBroadCast[0] + "." + arBroadCast[1] + 
           "." + arBroadCast[2] + "." + arBroadCast[3]);
}

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Software Developer Infineon Technologies
Austria Austria
.. was born
.. grew up

Comments and Discussions

 
Question[My vote of 1] is better Pin
Shargon_855-Aug-11 22:50
Shargon_855-Aug-11 22:50 
GeneralMy vote of 1 Pin
TylerBrinks5-Feb-09 10:15
TylerBrinks5-Feb-09 10:15 
GeneralMuch better solution Pin
Michal Brylka22-Aug-08 12:25
Michal Brylka22-Aug-08 12:25 
Hello, this should solve this problem faster:
public static IPAddress GetBroadcastAddress(IPAddress ipAddress, IPAddress subnetMask)
{
	byte[] ipab = ipAddress.GetAddressBytes();
	byte[] smb = subnetMask.GetAddressBytes();
	if (ipab.Length != smb.Length) throw new ArgumentException("Both IP address and subnet mask sholud be of the same length");
	byte[] result = new byte[ipab.Length];
	for (int i = 0; i < result.Length; i++)
		result[i] = (byte)(ipab[i] | (smb[i] ^ 255));
	return new IPAddress(result);
}


Best regards
Michał Bryłka

Theory is when you know something, but it doesn't work.
Practice is when something works, but you don't know why.
Programmers combine theory and practice: Nothing works and they don't know why.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.