MrRobot9
MrRobot9

Reputation: 2684

Get IP Address of pc from android device programmatically

I have connected my PC wired to the router, whereas my android device is wirelessly connected to the same router.

I need to access the nodejs server running on my machine from my app. I need to retrieve IP Address of the machine in Android app.

I have tried this code

    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    String ip =  Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    return ip;

ipconfig commands displays 192.168.1.100, whereas in code its returns 192.168.1.103 ....How do I make it get the IP Address of the machine in my app?

Upvotes: 0

Views: 3960

Answers (3)

mahmoud zaher
mahmoud zaher

Reputation: 554

This worked for me:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

Don't for get to give ACCESS_WIFI_STATE and other permissions in the manifest

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

Upvotes: 1

Ronny D&#39;Hoore
Ronny D&#39;Hoore

Reputation: 842

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.)

Upvotes: 2

Raizal I.N. Pregnanta
Raizal I.N. Pregnanta

Reputation: 109

See my gist here

I use it for my old project.

Upvotes: 1

Related Questions