在此基础上获取当前连接网络的IP
时间: 2023-12-04 20:01:59 浏览: 40
要获取当前连接网络的IP地址,你可以使用下面的代码来实现:
```java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
public class NetworkUtils {
public static String getIPAddress(Context context) {
String ipAddress = "";
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
ipAddress = getIPAddressFromNetworkInterface("eth0");
}
} else {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET && networkInfo.isConnected()) {
ipAddress = getIPAddressFromNetworkInterface("eth0");
}
}
}
return ipAddress;
}
private static String getIPAddressFromNetworkInterface(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface networkInterface : interfaces) {
if (networkInterface.getName().equalsIgnoreCase(interfaceName)) {
List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses());
for (InetAddress address : addresses) {
if (!address.isLoopbackAddress()) {
return address.getHostAddress();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
```
在上述代码中,getIPAddress()方法接收一个Context参数,通过ConnectivityManager获取当前连接的网络信息。然后根据网络类型,获取对应的IP地址。getIPAddressFromNetworkInterface()方法使用NetworkInterface类来获取指定网络接口的IP地址。
你可以在需要获取IP地址的地方调用getIPAddress()方法,传入当前的Context对象即可获得当前连接网络的IP地址。注意,如果是通过模拟器运行,可能无法获得真实的IP地址。