在Android应用上获取真实IP地址可以通过以下步骤实现:
ConnectivityManager
类获取设备的网络连接状态。NetworkInfo
类获取当前活动的网络连接。NetworkInterface
类获取设备的网络接口信息。NetworkInterface.getNetworkInterfaces()
方法获取设备的网络接口列表。NetworkInterface.getInetAddresses()
方法获取每个网络接口的IP地址列表。以下是一个示例代码,用于在Android应用上获取真实IP地址:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class IPAddressUtil {
private static final String TAG = "IPAddressUtil";
public static String getIPAddress(Context context) {
String ipAddress = null;
try {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// 获取WiFi网络的IP地址
ipAddress = getWifiIPAddress();
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// 获取移动网络的IP地址
ipAddress = getMobileIPAddress();
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to get IP address: " + e.getMessage());
}
return ipAddress;
}
private static String getWifiIPAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
return inetAddress.getHostAddress();
}
}
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to get WiFi IP address: " + e.getMessage());
}
return null;
}
private static String getMobileIPAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getName().equalsIgnoreCase("rmnet0")) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
return inetAddress.getHostAddress();
}
}
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to get mobile IP address: " + e.getMessage());
}
return null;
}
}
请注意,获取真实IP地址可能受到设备网络环境和权限限制的影响。此外,由于Android设备的网络配置可能因厂商和系统版本而异,上述代码可能需要根据实际情况进行适配和调整。
对于Android应用上获取真实IP地址的应用场景,可以用于网络诊断、用户行为分析、地理位置定位等功能。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云