アクティビティ内から、デバイスの IP アドレスを取得しようとしています。これを行うには、次のコードを使用しています。
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
しかし、この関数は正しいIPアドレスを返しません(おそらく、デバイスに指定されたプロキシIPではなく、ルーターIPを返します)。StackOverflow で多くのスレッドを実行しましたが、どれも役に立ちませんでした。
また、使用する予定はありません:
WifiManager wifiMan = (WifiManager) this.getSystemService(this.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
場合によっては、私のデバイスはワイヤレスではなく有線で接続されています
コードからデバイスの正しい IP アドレスを取得する方法を教えてもらえますか?
理想的には、デバイスが有線/無線で接続されていることを望み、デバイスの正しい IP アドレスを提供する必要があります。場合によっては、デバイスが有線接続されています。
助けてくれてありがとう。