2013-05-24 27 views
30

私の携帯電話のIPアドレスは無線LANで接続されているとどうすれば取得できますか?私のWiFiアドレスを取得するAndroid

私はメソッドhereを見つけましたが、私が無線LANの下にあっても24.182.239.255のようなものを返し、192.168.1.10のようなものを期待しています。

if (you are under wifi) 
    String ip4 = getWifiIP() 
else 
    String ip4 = getIPAddress with the method linked before 

感謝:

は、私のような何かをしたいと思います!

+0

あなたはプライベートIPを期待しているようです。これは役に立ちます。 http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device –

答えて

37

Wi-Fiに接続しているときにデバイスのプライベートIPアドレスを取得したい場合は、これを試すことができます。

WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE); 
WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); 
int ip = wifiInfo.getIpAddress(); 
String ipAddress = Formatter.formatIpAddress(ip); 

マニフェストに許可

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 

を追加してください。

+11

formatIpAddress()は推奨されていません。代わりに、InetAddress.getHostAddress()を使用して、以下のDigital Rouninによるソリューションを参照してください。 – Emmanuel

+1

ルーキーの場合のみ:getSystemService(Context.WIFI_SERVICE) – 10101010

+0

Endiannesは重要な考慮事項です。上記のコードは、リトルエンディアンハードウェアの逆IPを返します。正しい方法については、下記のDigital Rouninの答えを確認してください。または、より短いメソッド(intを正しい順序で返す)の場合は、http://stackoverflow.com/questions/29937433/gethostaddress-returns-a-reversed-ip-adressを参照してください。 –

61

ので、考慮すべき何かがFormatter.formatIpAddress(int)は廃止されていることである。

この方法は、IPv4とIPv6の両方のアドレスをサポートしているAPIレベル12 利用はgetHostAddress()で廃止されました。このメソッドはIPv6アドレスをサポートしていません。

したがって、formatIpAddress(int)を使用すると、長期的な解決策にはならない可能性がありますが、それはうまくいくでしょう。前回の回答で述べたように

protected String wifiIpAddress(Context context) { 
    WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); 
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); 

    // Convert little-endian to big-endianif needed 
    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { 
     ipAddress = Integer.reverseBytes(ipAddress); 
    } 

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); 

    String ipAddressString; 
    try { 
     ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress(); 
    } catch (UnknownHostException ex) { 
     Log.e("WIFIIP", "Unable to get host address."); 
     ipAddressString = null; 
    } 

    return ipAddressString; 
} 

、あなたはのAndroidManifest.xmlに以下のように設定する必要があります。ここでは

あなたは絶対に無線LANインターフェイスのIPアドレスを取得するために探している場合の潜在的なソリューションです

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 

これはほんの一例です。ヌル値などをチェックしてUXがスムーズであることを確認する時間が必要です。

一方、GoogleではformatIpAddress(int)を非難していますが、依然としてgetIpAddress()はまだ整数値を返しています。 IPアドレスがintであることも、IPv6に準拠しているためにそれを排除します。

次は、エンディアンが問題であるかどうかです。私は3つのデバイスしかテストしておらず、彼らはすべてリトルエンディアンでした。私たちがVMで動作していてもエンディアンはハードウェアによって異なるかもしれませんが、これは依然として問題となります。安全側にいるために、私はコード内にエンディアンチェックを追加しました。

getByAddress(byte[])は、整数値をビッグエンディアンにしたいと思われます。これを調べることで、ネットワークのバイトオーダーはビッグエンディアンに見えます。 192.168.12.22のようなアドレスはビッグエンディアンなので意味があります。


HammerNet GitHubプロジェクトを参照してください。上記のコードは、一連の健全性チェック、AVD、ユニットテストなどのデフォルトの処理能力とともに実装されています。私はこれを私のアプリ用に実装しなければならず、ライブラリをオープンソースにすることに決めました。

+0

Android StudioでBigIntegerをインポートできません。私はその奇妙なことを知っているが、それはそうだった。 – 10101010

+2

Nexus 5以降の端末では、エンディアン変換は実際には非常に重要です。ありがとう! – Danpe

+1

"WifiManager wifiManager =(WifiManager)context.getApplicationContext()。getSystemService(Context.WIFI_SERVICE)"これはまだ少し良いです。 – Denis

7

これは、WiFi IPv4、IPv6、またはその両方を取得します。

public static Enumeration<InetAddress> getWifiInetAddresses(final Context context) { 
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    final WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
    final String macAddress = wifiInfo.getMacAddress(); 
    final String[] macParts = macAddress.split(":"); 
    final byte[] macBytes = new byte[macParts.length]; 
    for (int i = 0; i< macParts.length; i++) { 
     macBytes[i] = (byte)Integer.parseInt(macParts[i], 16); 
    } 
    try { 
     final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); 
     while (e.hasMoreElements()) { 
      final NetworkInterface networkInterface = e.nextElement(); 
      if (Arrays.equals(networkInterface.getHardwareAddress(), macBytes)) { 
       return networkInterface.getInetAddresses(); 
      } 
     } 
    } catch (SocketException e) { 
     Log.wtf("WIFIIP", "Unable to NetworkInterface.getNetworkInterfaces()"); 
    } 
    return null; 
} 

@SuppressWarnings("unchecked") 
public static<T extends InetAddress> T getWifiInetAddress(final Context context, final Class<T> inetClass) { 
    final Enumeration<InetAddress> e = getWifiInetAddresses(context); 
    while (e.hasMoreElements()) { 
     final InetAddress inetAddress = e.nextElement(); 
     if (inetAddress.getClass() == inetClass) { 
      return (T)inetAddress; 
     } 
    } 
    return null; 
} 

使用法:

final Inet4Address inet4Address = getWifiInetAddress(context, Inet4Address.class); 
final Inet6Address inet6Address = getWifiInetAddress(context, Inet6Address.class); 

そして忘れてはいけない:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
1

をADBが端末にインストールされている場合は、操作を行います。

Runtime.getRuntime.exec("adb", "shell", "getprop", "dhcp.wlan0.ipaddress"); 
1

を私のクラッシュに基づいて、すべてのデバイスがWiFi macアドレスを返すとは限りません。

ここで最も一般的な返信のクリーン版です。

final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
final ByteBuffer byteBuffer = ByteBuffer.allocate(4); 
byteBuffer.order(ByteOrder.LITTLE_ENDIAN); 
byteBuffer.putInt(wifiInfo.getIpAddress()); 
try { 
final InetAddress inetAddress = InetAddress.getByAddress(null, byteBuffer.array()); 
} catch (UnknownHostException e) { 
    //TODO: Return null? 
} 
+0

'wifiInfo'とは何ですか、あなたのコードは不完全です – behelit

-1

Formatter.formatIpAddress(int型)が廃止されました:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); 
String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString(); 
+0

うん。 IPv6をサポートしません。 – aclokay

0

には、以下のパーミッションを追加します。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 

WifiManagerはonCreateで初期化します。

以下の機能を使用してください。

public void WI-FI_IP() { 
    WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); 
    int ip = wifiInfo.getIpAddress(); 
    String ipAddress = Formatter.formatIpAddress(ip); 
    } 
関連する問題