B4J Question GetBroadcastAddress multiple networks

techknight

Well-Known Member
Licensed User
Longtime User
I am having a problem getting the Broadcast Address from UDPSocket.GetBroadcastAddress because its only returning one of the IP addresses of whichever network it finds first on my PC which is an issue. my PC has 3 different networks on it, and I would like to be able to return an array of broadcast addresses for each network.

Thoughts? Thanks.
 

techknight

Well-Known Member
Licensed User
Longtime User
There's probably an easier way, but I got this to work:

B4X:
'Returns the UDP broadcast address.
'Returns an empty string if not available.
Sub GetBroadcastAddress As String()
    Dim IPList As List
    IPList.Initialize
    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
                    IPList.Add(b.SubString(1))
                End If
            Next
        End If
    Loop
    If IPList.Size > 0 Then         'Build an array from the list of broadcast IPs. 
        Dim ReturnIPArray(IPList.Size) As String
        For I = 0 To IPList.Size-1
            ReturnIPArray(I) = IPList.Get(I)
        Next
    Else
        Dim ReturnIPArray() As String        'If we dont have any available networks, just return an empty array. 
    End If
    Return ReturnIPArray
End Sub
 
Upvote 0
Top