vbnet Code:
  1. '
  2. Imports System.Net
  3.  
  4. Public Class IPv4Helpers
  5.  
  6.     Public Shared Function GetBroadcastAddress(ByVal ip As String, ByVal subnetMask As String) As String
  7.  
  8.         'Convert the IPv4 address and subnet mask from Strings to IPAdress objects
  9.         Dim ip_subnetMask As IPAddress = IPAddress.Parse(subnetMask)
  10.         Dim ip_addr As IPAddress = IPAddress.Parse(ip)
  11.  
  12.         'Use the subnet mask to get the subnet from the IP adress.
  13.         'Example: For the IP address 192.168.1.100 with a subnet mask of 255.255.255.0
  14.         'the subnet is 192.168.1.0
  15.         Dim subnet As UInteger = GetAddressBits(ip_subnetMask) And GetAddressBits(ip_addr)
  16.  
  17.         'Invert the subnet mask. Example: 255.255.255.0 becomes 0.0.0.255
  18.         Dim invertedMask As UInteger = Not GetAddressBits(ip_subnetMask)
  19.  
  20.         'Combine the inverted subnet mask with the subnet to get the broadcast address
  21.         'For example: The subnet 192.168.1.0 with an inverted mask of 0.0.0.255 becomes
  22.         '192.168.1.255
  23.         Return New IPAddress(BitConverter.GetBytes(invertedMask Or subnet)).ToString
  24.  
  25.     End Function
  26.  
  27.     Private Shared Function GetAddressBits(ByVal addr As IPAddress) As UInteger
  28.         Return BitConverter.ToUInt32(addr.GetAddressBytes, 0)
  29.     End Function
  30.  
  31.  
  32. 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:-
vbnet Code:
  1. '
  2.         Dim broadcastAddress As String = IPv4Helpers.GetBroadcastAddress("192.168.7.99", "255.255.255.0")
  3.  
  4.         Debug.WriteLine(broadcastAddress)

Which outputs the following:-
Code:
192.168.7.255