Hesam Ilyaei
Hesam Ilyaei

Reputation: 45

getting mobile network ip address

hello i'm using this method to get mobile network IP address

public static String getMobileIPAddress() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    return  addr.getHostAddress();
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions

    return "";
}

but the return value does not seems to be IP : fe80::dc19:94ff:fe6f:ae7b%dummy0

Upvotes: 1

Views: 404

Answers (2)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15433

Actually your code is correct. It's getting list of InetAddresses where ip address also present with mac address. You have to use InetAddressUtils.isIPv4Address or addr instanceof Inet4Address (API >= 23) to filter ip address among them. Check below:

public static String getMobileIPAddress() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress() && 
                    addr instanceof Inet4Address) {
                    return  addr.getHostAddress();
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
}

Upvotes: 1

Seyed Masood Khademi
Seyed Masood Khademi

Reputation: 173

This code get WIFI IP address:

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

Upvotes: 0

Related Questions