是否可以使用一些代码获得设备的IP地址?


当前回答

这是互联网上最简单的方法…… 首先,将此权限添加到您的manifest文件中…

“互联网” “ACCESS_NETWORK_STATE”

将此添加到Activity的onCreate文件中。

getPublicIP();

现在将这个函数添加到MainActivity.class中。

private void getPublicIP() { ArrayList<String> urls=new ArrayList<String>(); //to read each line new Thread(new Runnable(){ public void run(){ //TextView t; //to show the result, please declare and find it inside onCreate() try { // Create a URL for the desired page URL url = new URL("https://api.ipify.org/"); //My text file location //First open the connection HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setConnectTimeout(60000); // timing out in a minute BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate() String str; while ((str = in.readLine()) != null) { urls.add(str); } in.close(); } catch (Exception e) { Log.d("MyTag",e.toString()); } //since we are in background thread, to post results we have to go back to ui thread. do the following for that PermissionsActivity.this.runOnUiThread(new Runnable(){ public void run(){ try { Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show(); } catch (Exception e){ Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show(); } } }); } }).start(); }

其他回答

这是这个答案的返工,去掉了不相关的信息,添加了有用的评论,更清楚地命名变量,并改进了逻辑。

不要忘记包含以下权限:

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

InternetHelper.java:

public class InternetHelper {

    /**
     * Get IP address from first non-localhost interface
     *
     * @param useIPv4 true=return ipv4, false=return ipv6
     * @return address or empty string
     */
    public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces =
                    Collections.list(NetworkInterface.getNetworkInterfaces());

            for (NetworkInterface interface_ : interfaces) {

                for (InetAddress inetAddress :
                        Collections.list(interface_.getInetAddresses())) {

                    /* a loopback address would be something like 127.0.0.1 (the device
                       itself). we want to return the first non-loopback address. */
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddr = inetAddress.getHostAddress();
                        boolean isIPv4 = ipAddr.indexOf(':') < 0;

                        if (isIPv4 && !useIPv4) {
                            continue;
                        }
                        if (useIPv4 && !isIPv4) {
                            int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
                            ipAddr = delim < 0 ? ipAddr.toUpperCase() :
                                    ipAddr.substring(0, delim).toUpperCase();
                        }
                        return ipAddr;
                    }
                }

            }
        } catch (Exception ignored) { } // if we can't connect, just return empty string
        return "";
    }

    /**
     * Get IPv4 address from first non-localhost interface
     *
     * @return address or empty string
     */
    public static String getIPAddress() {
        return getIPAddress(true);
    }

}

虽然有一个正确的答案,我在这里分享我的答案,希望这样会更方便。

WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString();

我使用以下代码: 我使用hashCode的原因是因为当我使用getHostAddress时,我得到了一些垃圾值附加到ip地址。但是hashCode对我来说工作得很好,这样我就可以使用Formatter来获得具有正确格式的ip地址。

下面是示例输出:

1.使用 getHostAddress : ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0

2.使用hashCode和Formatter: ***** IP=238.194.77.212

如你所见,第二种方法正好满足了我的需求。

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()) {
                    String ip = Formatter.formatIpAddress(inetAddress.hashCode());
                    Log.i(TAG, "***** IP="+ ip);
                    return ip;
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(TAG, ex.toString());
    }
    return null;
}

下面的代码可能会帮助你..不要忘记添加权限..

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();
                }
           }
       }
       } catch (Exception ex) {
          Log.e("IP Address", ex.toString());
      }
      return null;
}

在清单文件中添加以下权限。

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

编码快乐! !