Finding “live” NAT interface and broadcast address for a UDP LAN Chat Program

Finding “live” NAT interface and broadcast address for a UDP LAN Chat Program

So I decided to do a simple Local Area Network based chat program that transmitted plaintext ASCII encoded text across UDP to all devices (listening on the port) on a network.

Little did I know it’s much harder than that when not all system Route Tables point to the interface’s global broadcast IPv4… v6 is another story.

In Visual Studio VB.NET we take a look at NetworkInformation import declaration to discover all Adaptors on our system, then we need to find the IP of the active network interface.

When you have VMWare, OpenVPN, and a plethora of other interfaces, finding the active one (with network connection) programmatically is a nightmare.


Using this snippet you’ll be able to find the local address of the Adaptor that is part of the local system and has a gateway attached. This is an interim solution and most likely only supports networks with routers (for their NAT):



Next, to determine global broadcast address you’ll need the current Subnet Mask for that adaptor/interface. Simply utilise the same Import System.Net.NetworkInformation:



Finally we need to use a bitwise comparison between the Subnet Mask and the current internal IPv4 to find the broadcast address. For example (local IP) with subnet mask ( would have the broadcast address of for that interface, and then with that information we can broadcast a LAN wide UDP datagram. Use this overly complicated bitwise comparison as an example of how to simply switch around the integers appropriately:



Then we can simply refer to the 3 functions to get our main broadcast address:

Dim broadcastAddress As String = FindBroadCastAddress(getIP(), getSubnetMask()).ToString()


Ok, now we make our program.

So using the broadcast address we can use Import System.Net to declare a listener and sender UdpClient.

Note: The following settings will be set as global vars/consts.

  • Private Const port As Integer = 13337
  • Private receivingClient As UdpClient
  • Private sendingClient As UdpClient
  • Private receivingThread As Thread
  • Private computerName As String = My.Computer.Name




Now for the listener we can utilise IPAddress(0) or IPAddress.Any to make sure our message is received on any active interface:



Add any functionality you see fit, like I’ve done with the Text Box hints!

Download my copy!


Leave a Reply

Your email address will not be published. Required fields are marked *