Android Question GetMyWifiIP returns local device's IP

DickD

Active Member
Licensed User
I'm trying to find the ip address of the wifi router my phone is currently connected to. I have tried the code below. It always returns the address of the phone I'm using now and not the router.

B4X:
Sub Process_Globals
 Dim Server As ServerSocket
 Dim router As String
End Sub

Sub Activity_Create(FirstTime As Boolean)
 Log("In FindWIFIusers")
 'Server.Initialize("5100","Server")
 router = Server.GetMyWifiIP
 Server.close
 Log("Router = " & router)
 Activity.Finish
End Sub
 

DonManfred

Expert
Licensed User
Longtime User
It always returns the address of the phone I'm using now and not the router
This is expected. MYwifiIP will give the Devices IP. NOT the routers IP.
 
Upvote 0

sz4t4n

Member
Licensed User
Longtime User
in most cases router IP is the same as the phone IP but the last value is 1 ex. 192.168.1.1. So just get your phone wifi IP and change the last value to 1.
 
Upvote 0

DickD

Active Member
Licensed User
in most cases router IP is the same as the phone IP but the last value is 1 ex. 192.168.1.1. So just get your phone wifi IP and change the last value to 1.
Yes, I considered that as a possibility but I'm worried about ... "in most cases". Isn't there something more dependable?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can use this code:
B4X:
Sub GetGatewayIp As String
   Dim ctxt As JavaObject
   ctxt.InitializeContext
   Dim WifiManager As JavaObject = ctxt.RunMethod("getSystemService", Array(ctxt.GetField("WIFI_SERVICE")))
   Dim dhcp As JavaObject = WifiManager.RunMethod("getDhcpInfo", Null)
   Dim formatter As JavaObject
   Return formatter.InitializeStatic("android.text.format.Formatter").RunMethod("formatIpAddress", Array(dhcp.GetField("gateway")))
End Sub
Based on this answer: https://stackoverflow.com/questions...ip-address-of-the-router-from-code-in-android

You need to add these permissions:
B4X:
AddPermission(android.permission.ACCESS_WIFI_STATE)
AddPermission(android.permission.CHANGE_WIFI_STATE)

Make sure to test it when there is no connection (I haven't tested it). Also note that it only works with IPv4 addresses.
 
Upvote 0
Top