安卓ServerSocket如何获取服务器的局域网IP地址?
在安卓平台上,可以通过以下步骤获取服务器的局域网IP地址:
以下是一个示例代码,演示如何获取服务器的局域网IP地址:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetworkUtils {
public static String getLocalIpAddress(Context context) {
try {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
String ipString = String.format("%d.%d.%d.%d",
(ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
return ipString;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getName().startsWith("eth") || networkInterface.getName().startsWith("wlan")) {
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) {
e.printStackTrace();
}
return null;
}
}
这段代码通过ConnectivityManager类获取网络连接信息,然后根据连接类型获取相应的IP地址。对于WiFi连接,使用WifiManager类获取IP地址;对于以太网连接,使用NetworkInterface类获取IP地址。最后返回获取到的局域网IP地址。
请注意,这只是一个示例代码,实际使用时可能需要根据具体情况进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云