Android 獲取本機WIFI及3G網絡IP


獲取本機WIFI
private
String getLocalIpAddress() { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // 獲取32位整型IP地址 int ipAddress = wifiInfo.getIpAddress(); //返回整型地址轉換成“*.*.*.*”地址 return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); }

 
          
3G網絡IP
public static String getIpAddress() {
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()
                            && inetAddress instanceof Inet4Address) {
                        // if (!inetAddress.isLoopbackAddress() && inetAddress
                        // instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
public String getLocalIpAddress() { String ipAddress = null; try { List<NetworkInterface> interfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface iface : interfaces) { if (iface.getDisplayName().equals("eth0")) { List<InetAddress> addresses = Collections.list(iface .getInetAddresses()); for (InetAddress address : addresses) { if (address instanceof Inet4Address) { ipAddress = address.getHostAddress(); } } } else if (iface.getDisplayName().equals("wlan0")) { List<InetAddress> addresses = Collections.list(iface .getInetAddresses()); for (InetAddress address : addresses) { if (address instanceof Inet4Address) { ipAddress = address.getHostAddress(); } } } } } catch (SocketException e) { e.printStackTrace(); } return ipAddress; }

  

需添加如下權限:

   <uses-permission android:name="android.permission.INTERNET" /> 

   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM