Android获取当前网络IP地址有多种方法,下面是其中一种常用的方法:
-
首先,在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
-
在代码中使用以下方法获取网络IP地址:
import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkInfo; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Collections; import java.util.List; public class NetworkUtil { public static String getIPAddress(Context context) { if (isNetworkConnected(context)) { try { List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : networkInterfaces) { List<InetAddress> inetAddresses = Collections.list(networkInterface.getInetAddresses()); for (InetAddress inetAddress : inetAddresses) { if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) { return inetAddress.getHostAddress(); } } } } catch (Exception e) { e.printStackTrace(); } } return null; } private static boolean isNetworkConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { Network network = connectivityManager.getActiveNetwork(); NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)); } else { NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } } return false; } }
-
在你的Activity或Fragment中调用这个方法来获取网络IP地址:
String ipAddress = NetworkUtil.getIPAddress(getApplicationContext());
以上是一种获取当前网络IP地址的方法,你可以根据自己的需求和情况选择合适的方法来获取。
要在Android上获取网络IP,可以使用以下方法之一:
- 使用Java的InetAddress类:
try {
InetAddress ipAddress = InetAddress.getLocalHost();
String ip = ipAddress.getHostAddress();
// 在这里使用获取到的ip
} catch (Exception e) {
e.printStackTrace();
}
- 使用第三方库,例如Apache的HttpClient:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpGet httppost = new HttpGet("http://ip-api.com/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
// 处理获取到的网络IP
} catch (Exception e) {
e.printStackTrace();
}
无论使用哪种方法,均需要在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.INTERNET" />
请注意,获取到的IP可能是设备连接的网络的IP,而不是设备自身的IP。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/146778.html