#CodeSnippet - Get android system IP Address
//Create an instance of WifiManager (API for managing all aspects of Wi-Fi connectivity) WifiManager wifiManager= (WifiManager) getSystemService(WIFI_SERVICE); //and in case of fragments WifiManager wifiManager= (WifiManager) getActivity().getSystemService(WIFI_SERVICE); //Returns a string in the canonical IPv4 format String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());A warning says : "The method formatIpAddress(int) from the type Formatter is deprecated".
This method was deprecated in API level 12.
Use getHostAddress(), which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses.
as per android docs Android DocsUse getHostAddress(), which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses.
So use formatIpAddress() because it works and add @SuppressWarnings("deprecation") to get rid of the warning.
//Create an instance of WifiManager (API for managing all aspects of Wi-Fi connectivity) WifiManager wifiManager= (WifiManager) getSystemService(WIFI_SERVICE); //WifiInfo the state of any Wifi connection that is active or is in the process of being set up //and getConnectionInfo() return dynamic information about the current Wi-Fi connection WifiInfo wifiinfo = wifiManager.getConnectionInfo(); byte[] myIPAddress = BigInteger.valueOf(wifiinfo.getIpAddress()).toByteArray(); // you must reverse the byte array before conversion. Find the Snippet here reverse(myIPAddress); InetAddress myInetIP = InetAddress.getByAddress(myIPAddress); String myIP = myInetIP.getHostAddress();
Comments
Post a Comment