Android Question java.lang.RuntimeException: java.net.BindException: bind failed: EADDRINUSE (Address already in use)

RB Smissaert

Well-Known Member
Licensed User
Longtime User
Just fixed a strange error that might be worth mentioning.
Some weeks ago I added some code to be able to send data (in my case just a SQL string) to other users on the WiFi network.
Taken from this example project posted by Erel:

All working fine, with no trouble at all.
Then yesterday I had a new phone (Samsung S25) and installed the app on that phone as well.
From then on I got on all the phones (only on every other app start) this error:

java.lang.RuntimeException: java.net.BindException: bind failed: EADDRINUSE (Address already in use)
at anywheresoftware.b4a.keywords.Common$14.run(Common.java:1750)
at android.os.Handler.handleCallback(Handler.java:959)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loopOnce(Looper.java:257)
at android.os.Looper.loop(Looper.java:342)
at android.app.ActivityThread.main(ActivityThread.java:9579)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:619)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)
Caused by: java.net.BindException: bind failed: EADDRINUSE (Address already in use)
at libcore.io.IoBridge.bind(IoBridge.java:149)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:162)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:427)
at java.net.ServerSocket.bind(ServerSocket.java:399)
at java.net.ServerSocket.<init>(ServerSocket.java:259)
at java.net.ServerSocket.<init>(ServerSocket.java:151)
at anywheresoftware.b4a.objects.SocketWrapper$ServerSocketWrapper.Initialize(SocketWrapper.java:314)
at b4a.exampleljjll.p_sqledit._initialize(p_sqledit.java:6684)
at b4a.exampleljjll.b4xmainpage$ResumableSub_CreatePage.resume(b4xmainpage.java:9887)
at b4a.exampleljjll.b4xmainpage._createpage(b4xmainpage.java:9377)
at b4a.exampleljjll.b4xmainpage$ResumableSub_InitApp.resume(b4xmainpage.java:32908)
at anywheresoftware.b4a.keywords.Common$14.run(Common.java:1748)
... 8 more
Caused by: android.system.ErrnoException: bind failed: EADDRINUSE (Address already in use)
at libcore.io.Linux.bind(Native Method)
at libcore.io.ForwardingOs.bind(ForwardingOs.java:138)
at libcore.io.ForwardingOs.bind(ForwardingOs.java:138)
at libcore.io.IoBridge.bind(IoBridge.java:145)
... 19 more

Error did never occur in debug mode and some trouble finding the cause but eventually tracked it down to this bit of code in my SQL page:

B4X:
Public Sub Initialize(iPageCode As Int) As Object

    server.Initialize(PORT, "server")
    ListenForConnections

This always ran on app startup.

Taking this out and only running

B4X:
    server.Initialize(PORT, "server")
    ListenForConnections

When I want to communicate with other devices solved the startup error and crash.
Next to see what happens when I run that after startup.
The strange thing about all this is that it only occurred after using that new S25.

RBS
 

DonManfred

Expert
Licensed User
Longtime User
at anywheresoftware.b4a.objects.SocketWrapper$ServerSocketWrapper.Initialize(SocketWrapper.java:314)
What does your ListenForConnections do? Is it setting up a server in some kind?
Seems like the adress-port combination is already in use. Maybe your app was already running (in background) and you are trying to setup another instance of the server.
 
Upvote 0

RB Smissaert

Well-Known Member
Licensed User
Longtime User
What does your ListenForConnections do? Is it setting up a server in some kind?
Seems like the adress-port combination is already in use. Maybe your app was already running (in background) and you are trying to setup another instance of the server.
B4X:
Type tWiFiConnectionPacket(strSQL As String, _
               strIP As String, _
               strDeviceID As String)

Private Sub ListenForConnections
    
    Do While bWorking
        server.Listen
        Wait For Server_NewConnection (bSuccessful As Boolean, NewSocket As Socket)
        
        If bSuccessful Then
            Dim rs As ResumableSub = CloseExistingConnection
            Wait For (rs) Complete (bDone As Boolean)
    
            client = NewSocket
            astream.InitializePrefix(client.InputStream, False, client.OutputStream, "astream")
            
            Dim rs As ResumableSub = PassDeviceID(False)
            Wait For (rs) Complete (bDone As Boolean)
            
            UpdateState(True)
        End If
    Loop
    
End Sub

Sub CloseExistingConnection As ResumableSub
    
    'so the connected device knows we have disconnected and update the dialog
    Dim rs As ResumableSub = PassDeviceID(True)
    Wait For (rs) Complete (bDone As Boolean)
    
    If astream.IsInitialized Then astream.Close
    If client.IsInitialized Then client.Close
    
    UpdateState (False)
    
    Return True
    
End Sub

Sub UpdateState(bNewState As Boolean)
    
    bConnected = bNewState
    
    If cMP.Dialog.IsVisible Then
        If cMP.Dialog.lblTitle.Text.StartsWith("SQL from ") Then
            UpdateTableConnections
            If Enums.strLastConnectedIPAddress.Length > 0 Then
                cMP.UpdateKVS("Enums.strLastConnectedIPAddress", Enums.strLastConnectedIPAddress)
            End If
        End If
    End If

End Sub

Sub UpdateTableConnections
    
    Dim i As Int
    Dim strIP As String
    Dim bSameIP As Boolean
    
    If bConnected Then
        For i = 0 To cMP.Dialog.tblDialog.NumberOfRows - 1
            strIP = cMP.Dialog.tblDialog.GetValue(1, i)
            bSameIP = (strIP = strConnectedToIP)
            cMP.Dialog.tblDialog.SetValue(2, i, IIf(bSameIP, "Yes", "No"))
        Next
    Else
        For i = 0 To cMP.Dialog.tblDialog.NumberOfRows - 1
            cMP.Dialog.tblDialog.SetValue(2, i, "No")
        Next
    End If

End Sub

Sub PassDeviceID(bDisconnected As Boolean) As ResumableSub 'ignore
    
    'to tell the connecting device what the device ID is of the device that was connected to
    '---------------------------------------------------------------------------------------
    Dim tWCP As tWiFiConnectionPacket
    tWCP.strSQL = "" 'to avoid error: on a null pointer object
    
    If bDisconnected Then
        tWCP.strIP = ""
    Else
        tWCP.strIP = Enums.strMyIP 'so the receiver knows the IP address of the sender
    End If
    
    tWCP.strDeviceID = Enums.strDeviceIdentifier 'so the receiver knows the Device ID of the sender
    
    Dim rs As ResumableSub = SendData(ser.ConvertObjectToBytes(tWCP))
    Wait For (rs) Complete (bDone As Boolean)
    
    Return bDone
    
End Sub

Public Sub SendData (data() As Byte) As ResumableSub
    
    If bConnected Then
        astream.Write(data)
    End If
    
    Return bConnected
    
End Sub

Sub UpdateState and UpdateTableConnections just deal with the interface and don't affect any connections.

RBS
 
Upvote 0

teddybear

Well-Known Member
Licensed User
As DonManfred said, a certain server has already bound this port. try to change the port.
 
Upvote 0

RB Smissaert

Well-Known Member
Licensed User
Longtime User
As DonManfred said, a certain server has already bound this port. try to change the port.
I have solved this now, so no crash anymore, but getting a different problem:
connection failed and the IDE shows this error:
Failed to connect: (ErrnoException) android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

Looked at all the permissions, but can't see what is causing this one.

RBS
 
Upvote 0

RB Smissaert

Well-Known Member
Licensed User
Longtime User
I think this is all fixed now, main thing was to only start the connection if that connection was not initialized yet:

B4X:
    If server.IsInitialized = False Then
        bWorking = True
        server.Initialize(PORT, "server")
        ListenForConnections
        lock.KeepAlive(False) 'will be released when we leave the SQL page or close this dialog
    End If

This runs just before showing the connection dialog, which shows a table with possible connections.

RBS
 
Upvote 0
Top