Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calculating the broadcast address for a subnet

0.00/5 (No votes)
22 Aug 2008 1  
How to calculate the broadcast address for a subnet.

Introduction

This code returns the Subnet-Broadcast-Address for a given IP-Address and Subnetmask.

I needed it for a WOL Funktion on a website which was in an different subnet and where the standard broadcastaddress didn't worked out.

Using the code

This function is quite easy and could be used for example in an UdpClient Object like this.

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

Code:

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]);
        }         

History

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here