vij
vij

Reputation: 143

How to get the IP address of a system using Android phone?

How to get the IP address of the PC using Android phone? (In particular how to fetch the IP address of a system with a specific MAC address, connected on the same network as the Android phone)?

       wired         wired    
modem--------router---------PC(mac:EE:00:B3:2F:56:12)
               |
               |
               |
             wireless
               |
               |
               |
               -------------android phone(A)  

Upvotes: 3

Views: 4402

Answers (1)

Igor F.
Igor F.

Reputation: 2699

private String getIP(String mac) {
  String ip = null;
  try {
    BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
    String line = "";
    while((line = br.readLine()) != null) {
      String[] tokens = line.split("\\s+");
      // The ARP table has the form:
      //   IP address        HW type    Flags     HW address           Mask   Device
      //   192.168.178.21    0x1        0x2       00:1a:2b:3c:4d:5e    *      tiwlan0
      if(tokens.length >= 4 && tokens[3].equalsIgnoreCase(mac)) {
        ip = tokens[0];
        break;
      }
    }
    br.close();
  }
  catch(Exception e) { Log.e(TAG, e.toString()); }
  return ip;
}

But beware: Unless you have already established contact with your PC (and you'll need either its IP address or its name), the ARP table will be empty.

I suppose you'd like to do it the other way round, establish the connection with the PC knowing only its MAC address. Then it's not that simple. You might try to ping everyone on the local network (Runtime.getRuntime().exec("ping -b 192.168.178.255");) just to fill the ARP table.

Or, maybe, you can get the list of all clients with their IP addresses from your router?

Upvotes: 3

Related Questions