How to get the system ip address after usb tethering of android phone?

只愿长相守 提交于 2019-12-03 21:02:05

Its not possible to find IP address created in PC from android after tethering. There is no API or other way to find it.

If you use InetAddress , it will return 192.168.42.129 - which is a DHCP address created by USB Tethering. It wont help you to communicate.

The other way is to scan the list of IP. USB Tethering will create ip ranging for 192.168.42.1 to 192.168.42.255 . You can write a simple scanner to find which one is active. But it will take some time.

rajesh

Thanks to 'Swim N Swim' above. I found a code at Retrieve IP and MAC addresses from /proc/net/arp (Android)

and modified a bit to get first IP having valid mac address. Works great when developing as a single user on your PC with tethered. You may follow above link for further selective IPs based on company name etc.

public static String getUSBThetheredIP() {

    BufferedReader bufferedReader = null;
    String ips="";

    try {
        bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            String[] splitted = line.split(" +");
            if (splitted != null && splitted.length >= 4) {
                String ip = splitted[0];
                String mac = splitted[3];
                if (mac.matches("..:..:..:..:..:..")) {
                    if (mac.matches("00:00:00:00:00:00")) {
                        //Log.d("DEBUG", "Wrong:" + mac + ":" + ip);
                    } else {
                        //Log.d("DEBUG", "Correct:" + mac + ":" + ip);
                        ips = ip;
                        break;
                    }
                }
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return ips;
}

Note that each time you tether after untether, you must start your apache or other processes on PC to take new IP effective. THis is what I experienced.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!