Android 取得 WiFi ip address

本篇 ShengYu 介紹 Android 取得 WiFi ip address 的寫法。

1
2
3
4
5
6
7
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
String ip = String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff));

加入存取權限,需要在 AndroidManifest.xml 裡加入 android.permission.ACCESS_WIFI_STATE,其他是我可能會用到的也順便加入

1
2
3
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Context WIFI_SERVICE | Android Developers
https://developer.android.com/reference/android/content/Context#WIFI_SERVICE
cameraserve/AndroidManifest.xml at master · arktronic/cameraserve
https://github.com/arktronic/cameraserve/blob/master/app/src/main/AndroidManifest.xml

其它相關文章推薦
Android MJPEG Streaming App