現在実行中のAndroid Emulatorの IP アドレスをコードで取得したいと考えています。どうすれば達成できますか?
7 に答える
Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.
Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.
Since you were asking only about the emulator's IP, what is it you're trying to do?
本当にエミュレータに IP を割り当てたい場合は、次のようにします。
adb shell
ifconfig eth0
次のようなものが得られます。
eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]
このような:
public 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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
詳細については、ドキュメントを確認してください: NetworkInterface。
この方法を使用すると、Android エミュレーターの 100% 正しい IP アドレスを取得できます
エミュレータのIPアドレスを取得するには
adb シェルに移動し、次のコマンドを入力します
adb shell
ifconfig eth0
このコマンドを実行した後、私は得ています
IP : 10.0.2.15
マスク : 255.255.255.0
私にとってはうまくいきます。私はネットワークアプリケーションにも取り組んでいます。
エミュレーター クライアントが同じホスト上で実行されているサーバーに接続する場合など、ホスト コンピューターのローカルホストを参照する必要がある場合は、エイリアス10.0.2.2を使用して、ホスト コンピューターのループバック インターフェイスを参照します。エミュレーターの観点から、localhost (127.0.0.1)は独自のループバック インターフェイスを参照します。詳細: http://developer.android.com/guide/faq/commontasks.html#localhostalias
public 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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}