web-dev-qa-db-ja.com

AndroidでwifiホットスポットのIPを取得する方法は?

タイトルにあるように...ホットスポットとして設定されている場合、wifiifaceのIPを取得できるようにしようとしています。理想的には、すべての電話で機能するものを見つけたいと思います。

もちろん、APから情報を取得する場合、WifiManagerは役に立ちません。

幸いなことに、これを行うことで、すべてのインターフェイスのIPを取得できました。

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()) {
                    Log.d("IPs", inetAddress.getHostAddress() );
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

このコードのチャンクは、すべてのインターフェイス(Wifiホットスポットを含む)のすべてのIPを出力します。主な問題は、WiFiインターフェイスを識別する方法が見つからないことです。一部の電話には複数のインターフェイス(WiMaxなど)があるため、これは問題です。これは私がこれまでに試したことです:

  • Wi-Fi ifaceの表示名によるフィルタリング:表示名がデバイスごとに変わるため(wlan0、eth0、wl0.1など)、これは適切なアプローチではありません。
  • Macアドレスによるフィルタリング:ほぼ機能しますが、一部のデバイスでは、ホットスポットifaceにMACアドレスがありません(iface.getHardwareAddress()はnullを返します)...したがって、有効な解決策ではありません。

助言がありますか?

15
sirlion

これが私がwifiホットスポットIPを取得するためにしたことです:

public String getWifiApIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            if (intf.getName().contains("wlan")) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && (inetAddress.getAddress().length == 4)) {
                        Log.d(TAG, inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(TAG, ex.toString());
    }
    return null;
}

これにより、anyWi-FiデバイスのIPアドレスがわかります。つまり、ホットスポットだけのものではありません。別のwifiネットワークに接続している場合(つまり、ホットスポットモードになっていない場合)、IPが返されます。

最初にAPモードになっているかどうかを確認する必要があります。そのためにこのクラスを使用できます: http://www.whitebyte.info/Android/android-wifi-hotspot-manager-class

8
ajma

あなたはそれを使うことができます。テストされていませんが、動作するはずです。

((WifiManager) mContext.getSystemService(Context.WIFI_SERVICE)).getDhcpInfo().serverAddress
2
navid_gh
private static byte[] convert2Bytes(int hostAddress) {
    byte[] addressBytes = { (byte)(0xff & hostAddress),
            (byte)(0xff & (hostAddress >> 8)),
            (byte)(0xff & (hostAddress >> 16)),
            (byte)(0xff & (hostAddress >> 24)) };
    return addressBytes;
}

public static String getApIpAddr(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
    byte[] ipAddress = convert2Bytes(dhcpInfo.serverAddress);
    try {
        String apIpAddr = InetAddress.getByAddress(ipAddress).getHostAddress();
        return apIpAddr;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return null;
}
0
yiteng lin

WiFiManagerConnectionInfoを利用して対応するNetworkInterfaceを見つける可能性のある solution を次に示します。

IPだけが必要な場合は、次を使用できます。

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
0
tenorsax

新しいメーカーから毎年新しい電話が出てくるので、ワイヤレスインターフェイスの名前を特定するだけで近い将来失敗するでしょう。次のメソッドは、getDhcpInfo()。serverAddressによって返される整数IPからリモートサーバーIPを取得できます。

public String getIPv4Address(int ipAddress) {
    // convert integer ip to a byte array
    byte[] tempAddress = BigInteger.valueOf(ipAddress).toByteArray();
    int size = tempAddress.length;
    // reverse the content of the byte array
    for(int i = 0; i < size/2; i++) {
        byte temp = tempAddress[size-1-i];
        tempAddress[size-1-i] = tempAddress[i];
        tempAddress[i] = temp;
    }
    try {
        // get the IPv4 formatted ip from the reversed byte array
        InetAddress inetIP = InetAddress.getByAddress(tempAddress);
        return inetIP.getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return "";
}

そうすれば、WiFiサービスを利用するアクティビティからこのように利用できます

WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String serverIp = getIPv4Address(wifi.getDhcpInfo().serverAddress);
Log.v("Server Ip", serverIp);

これにより、接続されているサーバーのIPが表示されます。

注:サーバーのIPを照会する前に、WiFi経由でアクセスポイント(ホットスポットなど)への接続が正常に作成されていることを確認してください。正常な接続を作成するために必要なのはSSIDとpreSharedkey(安全な場合)のみであり、サーバーのIPは必要ありません。

0
Udo E.

intf.getName().contains("wlan")intf.getName().contains("wl") || intf.getName().contains("ap")に変更して、ajmaのソリューションを使用します。そしてそれは多くの携帯電話で動作します。

ただし、WiFiに接続している場合はjust nullを返します。

0
brk

Wifiがホットスポットとして設定されていない場合、ホットスポットがオンになると_Android-xx7632x324x32423_ homeという名前になり、その名前はなくなります。また、IPアドレスも変更されます。

したがって、ホットスポットを有効にする前にWifi構成を取得できる場合は、まずintf.getName()を使用してホットスポットへの参照を取得できます。

次に、IPが変更されたため、wifiがCONNECTEDモードになっているインターフェースがわかっている場合は、ホットスポットを有効にした後で、その情報を使用して識別できます。

以下は、デバッグに使用したコードです。私は見つけたものをすべて吐き出し、大きな混乱を引き起こし、問題がわかったらそれをクリーンアップします。 GL

_import Java.net.InetAddress;
import Java.net.NetworkInterface;
import Java.util.Collections;
import Android.net.ConnectivityManager;

textStatus = (TextView) findViewById(R.id.textStatus);

try {
  for (NetworkInterface intf : Collections.list(NetworkInterface.getNetworkInterfaces())) {
    for (InetAddress addr : Collections.list(intf.getInetAddresses())) {
      if (!addr.isLoopbackAddress()){
        textStatus.append("\n\n IP Address: " + addr.getHostAddress() );
        textStatus.append("\n" + addr.getHostName() );
        textStatus.append("\n" + addr.getCanonicalHostName() );
        textStatus.append("\n\n" + intf.toString() );
        textStatus.append("\n\n" + intf.getName() );
        textStatus.append("\n\n" + intf.isUp() );
      } 
    }
  }
} catch (Exception ex) {
  textStatus.append("\n\n Error getting IP address: " + ex.getLocalizedMessage() );
}


connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
allInfo = connectivity.getAllNetworkInfo();
mobileInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

textStatus.append("\n\n TypeName: " + mobileInfo.getTypeName());
textStatus.append("\n State: " + mobileInfo.getState());
textStatus.append("\n Subtype: " + mobileInfo.getSubtype());
textStatus.append("\n SubtypeName: " + mobileInfo.getSubtypeName());
textStatus.append("\n Type: " + mobileInfo.getType());
textStatus.append("\n ConnectedOrConnecting: " + mobileInfo.isConnectedOrConnecting());
textStatus.append("\n DetailedState: " + mobileInfo.getDetailedState());
textStatus.append("\n ExtraInfo: " + mobileInfo.getExtraInfo());
textStatus.append("\n Reason: " + mobileInfo.getReason());
textStatus.append("\n Failover: " + mobileInfo.isFailover());
textStatus.append("\n Roaming: " + mobileInfo.isRoaming()); 

textStatus.append("\n\n 0: " + allInfo[0].toString());
textStatus.append("\n\n 1: " + allInfo[1].toString());
textStatus.append("\n\n 2: " + allInfo[2].toString());
_
0
Rit Man