Click here to Skip to main content
Licence Public Domain
First Posted 22 Aug 2008
Views 9,160
Bookmarked 7 times

Calculating the broadcast address for a subnet

By | 22 Aug 2008 | Article
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:

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

Here is the complete source 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]);
}

License

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

About the Author

Daniel Wernle

Software Developer
Infineon Technologies
Austria Austria

Member

.. was born
.. grew up

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Question[My vote of 1] is better PinmemberShargon_8522:50 5 Aug '11  
GeneralMy vote of 1 PinmemberAcoustic10:15 5 Feb '09  
GeneralMuch better solution PinmemberMichal Brylka12:25 22 Aug '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 22 Aug 2008
Article Copyright 2008 by Daniel Wernle
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid