How to Get Ip Address of the Device from Code

How to get IP address of the device from code?

With permission ACCESS_WIFI_STATE declared in AndroidManifest.xml:

<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"/>

One can use the WifiManager to obtain the IP address:

Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

How to get IP address of cellular network when device is connected to WiFi in Android

Whenever you enable WiFi on your device AND have an active connection to a WiFi network, your mobile data is temporarily disabled, no matter if you have enabled it manually or not. The setting "Mobile data on/off" is only taken into consideration if you have no active WiFi connection.

Some custom ROMs have an option to keep the mobile connection alive when you connect to a WiFi (so in case you lose your WiFi connection, it switches to mobile faster), but still, the WiFi connection is used.

Conclusion: You cannot get both IP addresses as you cannot have both WiFi and mobile network on (and if you can, you only use WiFi actively)

Get IP Address of pc from android device programmatically

Any app will either (1) allow the user to manually type a hostname or IP address of the server it needs to reach, or (2) a hostname will be hardcoded into the app.

Since you are operating on your own LAN, a hostname won't do, as no DNS server will resolve it.

So (1) will be the easiest route for you. Of course, you could store the IP so that you don't need to type it every time.

And your pc would need to have a static IP, instead of a dynamic (DHCP) IP. You can assign for example 192.168.1.99 as your DHCP range seems to start at 100. Make sure you also fill in the default gateway, and at least one DNS server. Type "ipconfig /all" (if it's a Windows pc) to find out the current values.

If your code does not need to be flexible, you could even hardcode that IP 192.168.1.99 into your app, so that you don't need to enter it.

(There are ways to scan the network for pc's that listen on a certain port, but these are not so easy to program, moreover, if more than one machine on your network would be running nodejs server, you would have no clue which one your app should access.)

Get my wifi ip address Android

If you would like to get the private IP address of your device when connected to Wi-Fi, you can try this.

WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);

Be sure to add the permission

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

to your manifest.



Related Topics



Leave a reply



Submit