方法一
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; }
方法二
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地址,需要訪問:
www.ip138.com才可以,然後解析文字即可。