可以通过网络接口获取,遍历所有的网络接口,但是有时可能会存在多个ip,那真正连网时使用的ip时哪一个的呢?可能不太好判断。可以通过另一种方式,使用Socket建立连接来获取正在使用的本地ip,代码如下:
private String getLocalIp() {
Socket socket = null;
try {
// 这里也可以使用ip,比如使用自己公司服务器的ip和端口
socket = new java.net.Socket("baidu.com", 80);
return socket.getLocalAddress().getHostAddress();
} catch (Exception e) {
Timber.Companion.fw(e, "尝试激活网络失败,无法连接到:" + host + ":" + port);
} finally {
IOUtil.closeIO(socket);
}
return null;
}
另外:
- socket.getLocalPort() 获取本地使用的网络端口
- socket.getInetAddress().getHostAddress() 获取远程连接的ip,如使用域名连接,可以获取到域名对应的ip
在问ChatGPT时得到了一个类似的答案,如下:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import java.net.InetAddress;
import java.util.Arrays;
public class NetworkUtils {
public static void getConnectedDevicesIP(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network[] networks = connMgr.getAllNetworks();
for (Network network : networks) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.isConnected()) {
Log.d("NetworkUtils", "Network: " + networkInfo.getTypeName());
getDeviceIPAddresses(network);
}
}
} else {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.d("NetworkUtils", "Network: " + networkInfo.getTypeName());
getDeviceIPAddresses(null);
}
}
}
private static void getDeviceIPAddresses(Network network) {
try {
InetAddress[] addresses = network != null ?
network.getAllByName("www.google.com") :
InetAddress.getAllByName("www.google.com");
Log.d("NetworkUtils", "IP Addresses: " + Arrays.toString(addresses));
} catch (Exception e) {
e.printStackTrace();
}
}
}