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  ..
            Asked
            
        
        
            Active
            
        
            Viewed 5.1k times
        
    7
            
            
         
    
    
        krishnan muthiah pillai
        
- 2,711
- 2
- 29
- 35
2 Answers
17
            
            
        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?
 
    
    
        Community
        
- 1
- 1
 
    
    
        rana_sadam
        
- 1,216
- 10
- 18
- 
                    2But it returns the first address it finds, for ipv4 it's fine since there is only one, but for ipv6 based addresses there are more than one, so how do i make sure that the first address it returns is the correct ipv6 address – Sumit Kumar Saha Sep 17 '17 at 09:16
15
            
            
        I used this and it workd !
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Below permissions in the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 
    
    
        Mohamed ALOUANE
        
- 5,349
- 6
- 29
- 60
- 
                    1
- 
                    1
- 
                    1
- 
                    Here is the method I use @natsumiyu: https://stackoverflow.com/a/54417079/2068732 – matdev Jul 04 '19 at 08:05
-