By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

Calculating the broadcast address given an IPv4 IP address and subnet mask.


Angel of Code
Nov 22, 2011
Imports System.Net

Public Class IPv4Helpers

Public Shared Function GetBroadcastAddress(ByVal ip As String, ByVal subnetMask As String) As String

'Convert the IPv4 address and subnet mask from Strings to IPAdress objects
Dim ip_subnetMask As IPAddress = IPAddress.Parse(subnetMask)
Dim ip_addr As IPAddress = IPAddress.Parse(ip)

'Use the subnet mask to get the subnet from the IP adress.
'Example: For the IP address with a subnet mask of
'the subnet is
Dim subnet As UInteger = GetAddressBits(ip_subnetMask) And GetAddressBits(ip_addr)

'Invert the subnet mask. Example: becomes
Dim invertedMask As UInteger = Not GetAddressBits(ip_subnetMask)

'Combine the inverted subnet mask with the subnet to get the broadcast address
'For example: The subnet with an inverted mask of becomes
Return New IPAddress(BitConverter.GetBytes(invertedMask Or subnet)).ToString

End Function

Private Shared Function GetAddressBits(ByVal addr As IPAddress) As UInteger
Return BitConverter.ToUInt32(addr.GetAddressBytes, 0)
End Function

End Class

The above is a simple class for calculating the broadcast address given an IPv4 IP address and a subnet mask. This is usually needed in Winsock applications that utilize UDP broadcasts as part of it's operation.

Here is an example of how to use it:-
Dim broadcastAddress As String = IPv4Helpers.GetBroadcastAddress("", "")


Which outputs the following:-