zoukankan      html  css  js  c++  java
  • 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"/>

     


  • 相关阅读:
    Java性能权威指南读书笔记--之二
    Java性能权威指南读书笔记--之一
    深入理解JVM-java字节码文件结构剖析(练习解读字节码)
    深入理解JVM-java字节码文件结构剖析(1)
    jvm(5)---垃圾回收(回收算法和垃圾收集器)
    jvm(4)---垃圾回收(哪些对象可以被回收)
    jvm(3)---常用监控工具指令
    jvm(2)---类加载机制
    jvm(1)---java内存结构
    Eureka客户端源码流程梳理
  • 原文地址:https://www.cnblogs.com/zgz345/p/3412958.html
Copyright © 2011-2022 走看看