B4J Question Wrong IP Address returned by ServerSocket GetMyIP

max123

Well-Known Member
Licensed User
Longtime User
Hi all,
B4X:
Private Sock As ServerSocket
Log("IP: " & Sock.GetMyIP)

If Sock.GetMyIP = "127.0.0.1" Then
    LogError("This library need network connection. Please connect and try again")
    Return
End If
This code worked well for ten years in all my PC and on all B4J and B4A projects.

Today while network is disconnected, B4J fails and returned the IP address of VirtualBox virtual network interface instead of the loopback interface (127.0.0.1).
At this point Copilot said me to disable on ControlPanel the VirtualBox network.
After I desabled it, B4J returned the Hyper-V IP address. Copilot at this point said that it depends on the networks priorities, to change the loopback priority to 1 and other virtuals to 5000 with Shell.
This do not changed before and after reboot. without network B4J always return the Hyper-V IP address.
I tried to completely disable Hyper-V and reboot, now B4J return an IPv6 address.
I tried to completely reset my network settings and reboot again, but nothing changed, It always return other IP address than loopback.

I always used all this things without any problem, all always worked, but now it fail.

The only way I found to get my real IP address or "127.0.0.1" is to use Inline Java or JavaObject to iterate all network interfaces, put here some filters to filter some IP addresses that way:
B4X:
' Return IPv4 IP Adress (Wi‑Fi/Ethernet) if present.
' If not found return "127.0.0.1" that point to loopback.
Public Sub GetRealIPv4 As String
    Dim NI As JavaObject
    NI.InitializeStatic("java.net.NetworkInterface")
    Dim enNI As JavaObject = NI.RunMethod("getNetworkInterfaces", Null)
    If enNI.IsInitialized = False Then Return "127.0.0.1"
 
    Dim foundIP As String = ""
 
    Do While enNI.RunMethod("hasMoreElements", Null)
        Dim NI As JavaObject = enNI.RunMethod("nextElement", Null)
        If NI.RunMethod("isUp", Null) = False Then Continue
        If NI.RunMethod("isLoopback", Null) = True Then Continue
 
        Dim enAddr As JavaObject = NI.RunMethod("getInetAddresses", Null)
        Do While enAddr.RunMethod("hasMoreElements", Null)
            Dim ia As JavaObject = enAddr.RunMethod("nextElement", Null)
            Dim ip As String = ia.RunMethod("getHostAddress", Null)
            Log(ip)
            If ip.Contains(":") Then Continue ' IPv6
            If ip.StartsWith("127.") Then Continue ' loopback
            If ip.StartsWith("169.254.") Then Continue ' APIPA (VirtualBox)
            ' Exclude private range 172.16.x.x - 172.31.x.x (Hyper-V)
            If ip.StartsWith("172.") Then
                Dim parts() As String = Regex.Split("\.", ip)
                Dim secondOctet As Int = parts(1)
                If secondOctet >= 16 And secondOctet <= 31 Then Continue
            End If
            foundIP = ip
            Exit ' trovato un IPv4 valido
        Loop
 
        If foundIP <> "" Then Exit
    Loop
 
    If foundIP <> "" Then
        Return foundIP
    Else
        Return "127.0.0.1"
    End If
End Sub

I want to know if this is a problem on my PC or if other users have similar results, or may
depends of latest B4J releases, or may depends from automatic Windows updates.
The fact is that now it fails and I never installed any other programs to change this, I just updated to B4J 10.30 and
some days ago I had to reboot my PC because operating system updates required it.

Now I still develop a library that require network and I cannot proceed.

Many thanks
 
Last edited:

max123

Well-Known Member
Licensed User
Longtime User
Thanks @Erel Here is the result with your code:
(ArrayList) [
[IsInitialized=true, Name=lo, DisplayName=Software Loopback Interface 1 , Address=127.0.0.1],
[IsInitialized=true, Name=eth3, DisplayName=VirtualBox Host-Only Ethernet Adapter , Address=169.254.228.152],
[IsInitialized=true, Name=wlan0, DisplayName=Intel(R) Dual Band Wireless-AC 7265 , Address=192.168.178.51],
[IsInitialized=true, Name=eth13, DisplayName=Hyper-V Virtual Ethernet Adapter , Address=172.24.160.1]
]
Without network Socket.GetMyIP see 169.254.228.152.
If I disable VirtualBox host it see 172.24.160.1
If I completely disable Hyper-V and reboot, it see an IPv6 address.

Here my ipconfig. Please some advices ?
1756144258153.png
 
Last edited:
Upvote 0

teddybear

Well-Known Member
Licensed User
I don't know you want to get an IP for what, but according to the code, it seems like you want to determine whether the network is available. if so, using IP to do that is incorrect
 
Last edited:
Upvote 0

Magma

Expert
Licensed User
Longtime User
Well I didn't understand what exactly you want... but I think... that if you need to work with virtualbox-image as a client at your network... so at the windows host pc, at network settings - at tcp/ip need to have and IP not already used.... an example if your local network using 192.168.1.1 for router, 192.168.1.11 your pc... at the ethernet that used from virtualbox (at windows host) put 192.168.232.1 (because don;t forget that will work as router) and subnet 255.255.255.0 (do not define gateway and dns)/ at settings of virtualbox machine (image), at network, check to use network card as NAT...

That is standard solution for using at network...

To get the real "public" ip, a nice trick at cmd is the following:
B4X:
nslookup myip.opendns.com resolver1.opendns.com

Non-authoritative answer and more specific at Address will show you the public ip

* one of many tricks to get the public ip
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
I forgot to say...

sometimes the problem comes from using TCP/IP v6...
1. The safest way for unproblematic local network is to use only tcp/ip v4 (untick the tcp/ip v6 protocols) at all the clients of network...
2. reboot router and clients...

enjoy your network..
 
Upvote 0

teddybear

Well-Known Member
Licensed User
I think VirtualBox and Hyper-V messed up the IP address.
There is no problem. GetMyIP returns correct ip and the code which Erel provided also returns correct IP list.
B4X:
Private Sock As ServerSocket
Log("IP: " & Sock.GetMyIP)

If Sock.GetMyIP = "127.0.0.1" Then
    LogError("This library need network connection. Please connect and try again")
    Return
End If
According to this snippet, I guess the OP's meaning is that when the getip is 127.0.0.1, the network is unavailable and the user be reminded to connect to the network first
 
Upvote 0

max123

Well-Known Member
Licensed User
Longtime User
I don't know you want to get an IP for what, but according to the code, it seems like you want to determine whether the network is available. if so, using IP to do that is incorrect
Thanks @teddybear. Yes, it is incorrect, but may I not explained well.

I always used Socket.GetMyIP to know if network is connected. I use B4X from ten years, not from ten days....
It always returned a software loopback if the network is not connected, and the real IP address if the network is connected.

Now when not connected it returns IP address of other interfaces depending on the interface enabled, never return a loopback to know if device has network.
It even return the same if the device is connected, so it always return any IP that is not a software loopback (127.0.0.1) and is not my machine IP address.

This always fail, if network is connected or not.
B4X:
    If mSock.GetMyIP = "127.0.0.1" Then
        LogError("TTS library need network connection. Please connect and try again")
        Return
    End If

To explain better, this code result in the log below:
B4X:
Log("Now I'm connected. My IP Address is " & mSock.GetMyIP & " but this is not the IP of my wlan OR lan, it is the IP of VirtualBox or if I disable it will change to Hyper-V")

' And here a part where I found my real IP iterating interfaces by code
    Dim ip As String = GetRealIPv4 ' The sub that iterate IPv4 interfaces, filter some address and return back the real IP or 127.0.0.1. But is just a fake'
    If ip = "127.0.0.1" Then
        Log("TTS library need network connection. Connect and try again. IP: " & ip)
        If SubExists(mCallback, mEventName & "_Ready") Then CallSub2(mCallback, mEventName & "_Ready", False)
    Else
        Log("TTS: Device connected. IP: " & ip & " This is my real IP of my wlan, but I had to iterate interfaces by code to get it")
        If SubExists(mCallback, mEventName & "_Ready") Then CallSub2(mCallback, mEventName & "_Ready", True)
    End If
And this is the result log. Something is really wrong :

TTS: Initializing TTS engine...
TTS: Device connected. IP: 192.168.178.51 This is my real IP of my wlan, but I had to iterate interfaces by code to get it
TTS: Ready: true
Now I'm connected. My IP Address is 169.254.228.152 but this is not the IP of my wlan OR lan, it is the IP of VirtualBox or if I disable it will change to Hyper-V
TTS: Speaking in [en] [32] Characters -> [Text to speech with Basic 4 Java]
Set language [en]
Start decoding: 24960 Bytes
Getting line from Audiosystem
TTS successfully completed: [Text to speech with Basic 4 Java]
I know that as @Erel said, this do not depends from B4J but from something that happen on my system, but if someone is expert on networks and can help me to figure how to fix it, I can provide the output of any command of the prompt or Shell. May change some networks order using Shell o other ways ?
It worked until some days ago..... or may I have to Restore back my system, but I've done this a lots of times on old Win XP, but not pratical on Windows 11, and my PC is very full of projects I've developed, this is dangerous without backups etc...

Many thanks
 
Last edited:
Upvote 0

max123

Well-Known Member
Licensed User
Longtime User
Thanks @Magma , I don't know at all what you mean, this is not for public IP address but for local pc address and pc software loopback.
I don't have to do nothing of particular, that see with Socket.GetMyIP if the PC is connected.
VirtualBox created itself the network when I installed it a lot of time ago, I enabled Hyper-V from 3 years from when I have this PC, all worked well until some days ago, I never had any problem until now.

I forgot to say...

sometimes the problem comes from using TCP/IP v6...
1. The safest way for unproblematic local network is to use only tcp/ip v4 (untick the tcp/ip v6 protocols) at all the clients of network...
2. reboot router and clients...

enjoy your network..
I don't use at all IPv6, I only use IPv4, and never seen IPv6 addresses until now while use ipconfig, where I have to untick IPv6 on my Fritzbox router ?
You said on the client side, so on Windows ? Probably automatic update changed something wrong ?
Sorry but I'm not very pratical with networks, I never changed it.
 
Last edited:
Upvote 0

MicroDrie

Well-Known Member
Licensed User
Longtime User
It hard to give a solution in this complicated setup.
I don't use at all IPv6, I only use IPv4, and never seen IPv6 addresses until now while use ipconfig, where I have to untick IPv6 on my Fritzbox router ?
That is correct, if you don't need IPv6 as you wrote.

You said on the client side, so on Windows ?
Yes somewhere in the network more adaptor options.

Probably automatic update changed something wrong ?
Maybe, it's always possible after a Windows or program update.

Sorry but I'm not very pratical with networks, I never changed it.
It's important to realize that there are non-routable addresses like your Scheda LAN wireless Wi-Fi: Gateway predefinito 192.168.178.1, the Scheda Ethernet vEthernet (Default Switch) : without a gateway address so no traffic can leave that subnet because a client don't know where the router lives. So there must be another client on that subnet which function is to route the traffic out of the subnet. So I guess the Fritz.Box is the router for the 192.168.178.1 subnet.
I don't know where the address for the Scheda Ethernet Ethernet 7: Automatically configured IPv4 address: 169.2514.228.152
with a subnet mask of 255.255.0.0 and without a Gateway address lives. Again no traffic can leave the subnet via a router. Some times you see this when an interface is not correctly initiated, such strange addresses is the default burn-in address of the interface.
You speak about Hyper-V IP address and VirtualBox network, I know without experience that this is a complicated network configuration.
A replay from network address 127.0.0.1 (which lives before the firewall) doesn't say anything about network connectivity. The only thing what is said, is that there software network active is a live, but the network traffic can still be blocked by the firewall.
How the traffic is flow through your network is with the command tracert to <destination address> for TCPv4.
Windows can have, but not necessary a routing table that can be used to route the traffic from a non-routable sub net to your fritz-box.
Maybe the best bet is to look to the Scheda Ethernet Ethernet 7 with IPv4 address: 169.2514.228.152 is a routeable public address on a Windows machine looks very strange to me because with such address traffic should normally not pass your fritz-box router interface for the 192.168.178.1 subnet. Again, you can make this working, but it looks to me unlike the case.
It's also imported the understanding that a replay from network address means that the software network is only meaning that the network software was started and that the network connectivity from the Windows machine can be blocked by a firewall or a misconfiguration in the network (router).
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
There is no problem. GetMyIP returns correct ip and the code which Erel provided also returns correct IP list.
This is a problem.
But I may be wrong. What I understand is GetMyIP assumed the pc only have one network card.
When we install virtualization software, it installed a virtual device driver and tricks the OS that it has another network card thus affected the behavior of the networking system.
So now the OP windows seems to have 3 network cards. This happened especially when we set them as bridge.
What I can say is either disable/don't use those virtualization softwares and continue to use GetMyIP to detect WAN/LAN
or
find another workaround.

The most easiest way I will use is calling an API or webservice or check whether opening google.com return expected output using OkHttpUtils2.
 
Upvote 0

teddybear

Well-Known Member
Licensed User
The most easiest way I will use is calling an API or webservice or check whether opening google.com return expected output using OkHttpUtils2.
This is one of the solutions for checking network whether it is available
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
TCP/IP v6 Disable/Enable
OK the fastest way to get at Network Adapter Settings (do that at all your network clients - pcs)

[WIN Key]+[R] paste: rundll32.exe shell32.dll,Control_RunDLL ncpa.cpl [Enter]

Right Click on every Network Adapter and select Properties
1756274122977.png


Follow following Video from the point set - to see how enable-disable tcp/ip v6 protocol:

Make the changes to all your pcs, reboot them...
* No need to change Router settings (just restart it too when end with settings)
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
Set at your Windows Host (the pc have installed VirtualBox Application) the right IP to be Router/Gateway for virtualbox machine image (running on it)

Go again at network adapters...

[WIN Key]+[R] paste: rundll32.exe shell32.dll,Control_RunDLL ncpa.cpl [Enter]

Right Click on every Network Adapter and select properties

1756274122977.png


Go at TCP/IP v4 (no at tick box) but selecting the protocol row and then click on properties...

For example if your router has 192.168.168.1, then you must make your pc have the last two range different... perhaps
192.168.56.1 and fill only the subnet...
1756274648864.png

from now on this Adapter will be used as Gateway for the virtualbox Machine if ofcourse is setupped right... at virtualbox settings...

For example...
at Oracle Virtualbox - right click on your machine image - select settings, then network, enable network card if not already, and select NAT...

1756274798269.png



If all these failed for you... copy all virtual machine images (or better virtualbox folder with images) - uninstall any virtualbox app from control panel / add remove apps, reboot your pc, install again your virtualbox following exactly the information at screen, reboot your pc, go at virtualbox and import the virtualbox machines you saved before...

If not worked... possible has to to do with settings in virtualbox machine... make a new to see if works and see the settings to know what changed...

ps: have in mind that you can work also in BRIDGE mode at network settings of virtualbox... and have it as another pc into you local network... but for me this is not right
 
Upvote 0

max123

Well-Known Member
Licensed User
Longtime User
Thanks peoples for help,

The most easiest way I will use is calling an API or webservice or check whether opening google.com return expected output using OkHttpUtils2
to @aeric and @teddybear yes I already done this, but the problem is that make an http request while there is network, it will work successfully, if there is no network, the log show the error that seem I cannot avoid. Because I have to use this for a library I don't like it, instead I wanted to log only my error.

I've used this code, but anyway this have nothing to do with the problem that Socket.GetMyIP return wrong IP address. Before now I never had the necessity to make an http request to know if the device is connected, I do this only to get the public ip address, so the true problem is a wrong network configuration inside Windows. After this will work I can continue to use Socket.GetMyIP.
B4X:
    ' 1. Test connettività
    Dim j As HttpJob
    j.Initialize("", Me)
    ' Endpoint leggero e affidabile
    j.Download("https://www.google.com/generate_204")
    j.GetRequest.Timeout = 3000 ' 3 secondi per evitare attese lunghe
 
    Wait For (j) JobDone(j As HttpJob)
    Dim online As Boolean = (j.Success And j.Response.StatusCode = 204)
    j.Release
 
    If Not(online) Then
        Log ("Your device is not connected. Please connect and try again.")
        Return "127.0.0.1"
    End If

As for @Magma suggertion now I completely disabled IPv6 on my Fritz and on my Windows, now Socket.GetMyIP return my real IP when online, but return wrong IP (not the software loopback 127.0.0.1) when not online. Instead it see VirtualBox network IP. Disabling the VirtualBox network it see Hyper-V IP address.

@Magma now I will read better last two your messages and your advices, I'm a bit busy here.
EDIT: I read a bit better, but I had no more time to test all things. But this set the static IP address instead to use DHCP, I don't want to do this.
The problem here is that (after I having this problem some days ago) I uninstalled from Control Panel the additional networks for VirtualBox and Hyper-V
they are duplicated for some reasons, like the same but with #2 or #3 index, but I only doing this after the problem occoured, not before.
Now suppose that VirtualBox do not exists, I have it installed but last time I've used it one year ago, so now I will completely uninstall and it is another problem removed.
Hyper-V cannot be uninstalled, only disabed, this way the default switch will be removed, but I don't want to disable it.

But the big problem is that this only happen when I use Socket.GetMyIP on B4J, using ipconfig and from Windows settings all seem ok but something in background is wrong, may network metrics and interfaces priorities.

Now I will try to completely uninstall VirtualBox, but for sure after that it see Hyper-V.
 
Last edited:
Upvote 0

Magma

Expert
Licensed User
Longtime User
Hyper-V is something supported or not... and this you can check it at your BIOS... if Hardware Virtualization is Enabled (if has this feature ofcourse) - i believe that all motherboards/cpu supporting that after 2013~2015.

metric can be a problem.. but this need to change some settings to be there... as i ve understand you didn't change anything... so keeping virtualbox machines (folder of vhd, or whatever) and uninstall, re-install with reboots at the middle... and then import the virtual machines... will help

Will recreate automatically the adapter needs...

ps: Windows Home editions... not supporting Hyper-V !
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
This works for me (getmyip seems to be using cached data after ethernet disconnected)
B4X:
    Try
        Dim jo As JavaObject
        jo.InitializeStatic("java.net.InetAddress")
        Dim addr As JavaObject = jo.RunMethod("getByName", Array("8.8.8.8"))
        Dim reachable As Boolean = addr.RunMethod("isReachable", Array(1000)) ' timeout in ms
        If reachable Then
            Log("OK") ' has internet
        Else
            Log("FAIL") ' no internet
        End If
    Catch
        Log("FAIL (exception)") ' no internet
    End Try

And I have Hyper-V and VirtualBox installed with no problems.
 
Upvote 0

Magma

Expert
Licensed User
Longtime User
B4X:
    ' 1. Test connettività
    Dim j As HttpJob
    j.Initialize("", Me)
    ' Endpoint leggero e affidabile
    j.Download("https://www.google.com/generate_204")
    j.GetRequest.Timeout = 3000 ' 3 secondi per evitare attese lunghe
 
    Wait For (j) JobDone(j As HttpJob)
    Dim online As Boolean = (j.Success And j.Response.StatusCode = 204)
    j.Release
   
    If Not(online) Then
        Log ("Your device is not connected. Please connect and try again.")
        Return "127.0.0.1"
    End If

Well at this point... i wanna say me experience.. ofcouse not sure if this is the right place... but...

B4X:
...
    wait for (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        Return j.GetString
    Else
        Try
            If j.GetString.Length>0 Then
                'Return j.ErrorMessage
                Return j.ErrorMessage'& " - Unknown Error"
            End If
        Catch
            Log(LastException)
        End Try
    End If
..

If use ELSE and then have Try Catch End Try....
and haven't a success... it may return me the previous (the right one - 10min before) cached - j.GetString

This ofcourse can be my error - or something wrong i ve did... but I am curious for the right solution... to get back error messages..
 
Upvote 0

max123

Well-Known Member
Licensed User
Longtime User
Hyper-V is something supported or not... and this you can check it at your BIOS... if Hardware Virtualization is Enabled (if has this feature ofcourse) - i believe that all motherboards/cpu supporting that after 2013~2015.

metric can be a problem.. but this need to change some settings to be there... as i ve understand you didn't change anything... so keeping virtualbox machines (folder of vhd, or whatever) and uninstall, re-install with reboots at the middle... and then import the virtual machines... will help

Will recreate automatically the adapter needs...

ps: Windows Home editions... not supporting Hyper-V !
Yes, for Hyper-V there are options on BIOS, I enabled it, but after that it can be enabled from here, this after reboot will remove any Hyper-V thing even the network swith that cannot be disabled by user when Hyper-V is active. I already tried to do this, but after that B4J see another IP address that is not a loopback anyway.
1756285178065.png

I already do a full network reset, 3 times... and this solved nothing
 
Upvote 0
Top