獲取本地的IP地址(內網)

方法一socket

    public static 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();
                    Log.e("XXX", inetAddress.getHostAddress());
                    if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

方法二ide

    private static void getIpAddress() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Socket socket = null;
                try {
                    socket = new Socket("www.baidu.com", 80);// 只有這個能夠
                                                                // 可是這個內網地址有沒有外網的地址呢?
                    Log.e("XXX", "socket : "
                            + socket.getLocalAddress().toString() + "\n");
                } catch (Exception e) {
                    e.printStackTrace();

                } finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

以上方法獲取到的地址是大都是內網的IP地址,如需獲取公網的IP地址,須要訪問:oop

www.ip138.com才能夠,而後解析文本便可。spa

相關文章
相關標籤/搜索