1

My laptop it connected to my router in the pc room. Now each time i shut down my laptop and connect it again i get a new ip address. In my android device i want to use the laptop ip address but i need each time to use my pc log in to the router settings and find the laptop ip address.

What i want to do is to scan all the ip's in the network all the ip's that connected to the router network and then find the ip address that fit to the laptop mac address so i know this is my laptop ip address.

I have this two methods but i'm not sure how to use the first one the refreshArp:

private static void refereshArp(Context ctx){
    //IP aquisition from http://stackoverflow.com/a/6071963/1896516
    WifiManager wm = (WifiManager) ctx.getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    String[] parts = ip.split(".");
    String subnet = parts[0] + "." + parts[1] + "." + parts[2] + ".";
    Runtime rt = Runtime.getRuntime();
    for(int i=0; i<256; i++){
        try{
            rt.exec("ping -c1 " + subnet + i)
        }catch(IOException e){
            continue;
        }
    }

}

What should the refreshArp get ?

The second method seems to be more easy to use just to give the laptop mac address:

//Adapted from http://www.flattermann.net/2011/02/android-howto-find-the-hardware-mac-address-of-a-remote-host/
private static String getIpFromMac(String mac) {
    if (mac == null)
        return null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");
            if (splitted != null && splitted.length >= 4 && mac.equals(splitted[3])) {
                // return the ip of the device
                return splitted[0];
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

Another problem is where to call from to this two methods ? From in the onCreate in the MainActivity ?

I'm using for my java code android studio 1.3.2

  • There's not a great way to do this, but you could (potentially) configure your dhcp server to give your laptop the same IP address (by the MAC address). Another option might be to write your machine's IP into a database on startup, and then query the database from android. – Elliott Frisch Sep 17 '15 at 23:17

0 Answers0