B4J Question Getting Pi Host IP Address

lip

Active Member
Licensed User
Longtime User
My Raspberry Pi's run a program on startup and then they need to send their IP address to my server.

The code below initially worked and still works, sometimes, but more often it returns what looks like an IPv6 address rather than IPv4. My understanding is that GetMyIP should return IPv4 if it is available.

Is it because I open the socket, get the IP, then close the socket, then start the Server? If so, how come it still works some of the time? I have to close the socket else I get a message saying that the port is already in use.

Dim mySocket As ServerSocket
Dim myLocalIP As String
Dim myServer As Server

B4X:
Sub AppStart (Args() As String)
  
    'An attempt to get local IP
    mySocket.Initialize(8888,"")
    myLocalIP = mySocket.GetMyIP
    Log(DateTime.Time(DateTime.Now) & " MyIP is " & myLocalIP)
    mySocket.Close

    'Start Server (eg http://192.168.1.26:8888/Setup)
    myServer.Initialize("myServer")
    myServer.Port = 8888
    myServer.StaticFilesFolder = File.Combine(File.DirApp,"www")
    myServer.AddHandler("/Setup","SetupPage",False)
    myServer.AddHandler("/StopCollator","StopCollator",False)      
    myServer.AddHandler("/PreferredMac","PreferredMac",False)      

    myServer.Start
 
Top