Android Code Snippet UDP Broadcast Address

This code uses JavaObject to go over the device network interfaces and find the first UDP broadcast address.
This address can be used to send a UDP packet to all devices listening to a specific port.

B4X:
'Returns the UDP broadcast address.
'Returns an empty string if not available.
Sub GetBroadcastAddress As String
   Dim niIterator As JavaObject
   niIterator = niIterator.InitializeStatic("java.net.NetworkInterface").RunMethod("getNetworkInterfaces", Null)
   Do While niIterator.RunMethod("hasMoreElements", Null)
     Dim ni As JavaObject = niIterator.RunMethod("nextElement", Null)
     If ni.RunMethod("isLoopback", Null) = False Then
       Dim addresses As List = ni.RunMethod("getInterfaceAddresses", Null)
       For Each ia As JavaObject In addresses
         Dim broadcast As Object = ia.RunMethod("getBroadcast", Null)
         If broadcast <> Null Then
           Dim b As String = broadcast
           Return b.SubString(1)
         End If
       Next
     End If
   Loop
   Return ""
End Sub
 
Top