Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ip address of an android mobile programatically ....? [duplicate]

Tags:

android

I want exact IP address of android device when it will connected to a network through wifi! can any one help me how to get the ip address while the mobile is connected to a network and how to get the address through pro-grammatically ..enter image description here

like image 341
krishnan Avatar asked Oct 16 '14 10:10

krishnan


People also ask

How do I find IP address on Android phone?

Go to Settings >> Wireless & networks/WLAN, or Settings >> Network & Internet >> Wi-Fi. Tap on the Wi-Fi you are connected to, then it will show the network info including signal strength, security, MAC address and IP address.

How do I find the IP address in Android programmatically?

getByIndex(int index) Get a network interface given its index. getByInetAddress(InetAddress addr) Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it. getByName(String name) Searches for the network interface with the specified name.

How do I locate my IP address?

On an Android/tabletGo to your Wifi network settings, then select the network you're connected to. You'll find your IP address along with the other network information.

How do I find public IP address programmatically?

you need to create a function in Activity. class file, and need to request a url that will give your public IP in text form: "https://api.ipify.org/. Click to open. Add this function call in your onCreate() function.


1 Answers

You can use this method to get IP address of the device pass true for IPv4 and false for IPv6

 public static String getIPAddress(boolean useIPv4) {
    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()) {
                    String sAddr = addr.getHostAddress();
                    //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    boolean isIPv4 = sAddr.indexOf(':')<0;

                    if (useIPv4) {
                        if (isIPv4) 
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
                            return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (Exception ex) { } // for now eat exceptions
    return "";
}

Thanks to this ans How to get IP address of the device?

like image 132
rana_sadam Avatar answered Sep 22 '22 23:09

rana_sadam