如何编程获得Android设备的公共IP地址?

hs1ihplo  于 2022-12-21  发布在  Android
关注(0)|答案(3)|浏览(156)

我想检索公共IP地址,我们得到的地址,例如从whatismyipaddress.com,我不想使用任何第三方servcie https://www.ipify.org .有没有办法从Android的内置类或库获取此IP地址.
如果无法从Android库中获取所需的数据,请建议任何逻辑以在服务器级别获取相同的数据,而不是在客户端级别获取。在路由到实际Web应用程序之前,负载平衡器已存在

kwvwclae

kwvwclae1#

我在我的项目中使用此方法..所以您可以使用它..它将返回您的设备IP

private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}

如果你想得到你的设备连接使用此代码的网络的公共IP ...

public class GetPublicIP extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... strings) {
        String publicIP = "";
        try  {
            java.util.Scanner s = new java.util.Scanner(
                    new java.net.URL(
                            "https://api.ipify.org")
                            .openStream(), "UTF-8")
                    .useDelimiter("\\A");
            publicIP = s.next();
            System.out.println("My current IP address is " + publicIP);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        return publicIP;
    }

    @Override
    protected void onPostExecute(String publicIp) {
        super.onPostExecute(publicIp);

        Log.e("PublicIP", publicIp+"");
        //Here 'publicIp' is your desire public IP
    }
}

新执行它

new GetPublicIP().execute();
disho6za

disho6za2#

使用此方法可获取您的IpAddress

public static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress();

                        boolean isIPv4 = sAddr.indexOf(':')<0;

                        if (useIPv4) {
                            if (isIPv4) 
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); 
                                return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) { } 
        return "";
    }
lfapxunr

lfapxunr3#

有了Kotlin和协程,

private suspend fun getMyPublicIpAsync() : Deferred<String> =
        coroutineScope {
            async(Dispatchers.IO) {
                var result = ""
                result = try {
                    val url = URL("https://api.ipify.org")
                    val httpsURLConnection = url.openConnection()
                    val iStream = httpsURLConnection.getInputStream()
                    val buff = ByteArray(1024)
                    val read = iStream.read(buff)
                    String(buff,0, read)
                } catch (e: Exception) {
                    "error : $e"
                }
                return@async result
            }
        }

private fun myFunction() {
   CoroutineScope(Dispatchers.Main).launch {
      val myPublicIp = getMyPublicIpAsync().await()
      Toast.makeText(this@MainActivity, myPublicIp, Toast.LENGTH_LONG).show()
   }
}

相关问题