學習筆記-Android客戶端獲取IP地址
阿新 • • 發佈:2018-11-06
Android獲取Ip的一些方法,在我們開發中,有判斷手機是否聯網,或者想獲得當前手機的Ip地址,當然WIFI連線的和
3G卡的Ip地址當然是不一樣的.
以這種方法不可取!
首先我嘗試瞭如下方法:
最後查了一些資料,發現如下方法是比較通用的,我嘗試了WIFI和G3卡,都獲取了正確的Ip地址程式碼如下:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
當我的手機處於飛行狀態是,獲得Ip地址為空,剛好符合要求!!!當我的手機處於飛行狀態是,獲得Ip地址為空,剛好符合要求!!!public String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(LOG_TAG, ex.toString()); } return null; }