編輯:關於Android編程
本文實例講述了android實現獲取有線和無線Ip地址的方法。分享給大家供大家參考。具體如下:
做android的開發時,遇到了獲取有線ip地址的問題.不多說 上代碼!
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
ipaddress = inetAddress.getHostAddress().toString();
if(!ipaddress.contains("::")){//ipV6的地址
return ipaddress;
}
}
}
} else {
continue;
}
}
分析:
先看這段代碼:
復制代碼 代碼如下:
intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")
這裡表示:僅過濾無線和有線的ip. networkInterface是有很多的名稱的 比如sim0,remt1.....等等.我不需要用到就直接過濾了
再看這段:
復制代碼 代碼如下:
if(!ipaddress.contains("::")){//ipV6的地址
這裡表示: 過濾掉ipv6的地址.不管無線還是有線 都有這個地址, 我這邊顯示地址大體是:fe80::288:88ff:fe00:1%eth0 fe80::ee17:2fff:fece:c0b4%wlan0 一般都是出現在第一次循環.第二次循環就是真正的ipv4的地址.
希望本文所述對大家的Android程序設計有所幫助。
Android程序報錯程序包org.apache.http不存在問題的解決方法
Android Studio 2.1中使用 Android SDK 6.0(API 23),加載融雲Demo時,報錯:解決辦法:Android 6.0(api 23)已經
Android源碼解析--SwipeMenuListView仿QQ聊天左滑
緒論:好久沒寫博客了,最近比較懶,不想寫博客,但是在看書,看一些Android進階的書,這裡小編也給大家推薦幾本適合進階的書,相信會對你有所幫助的。1.《Android群
Android開發 二 IPC機制(下)
我們繼續來講IPC機制,在本篇中你將會學習到ContentProvider Socket Binder連接池一.使用ContentProvider ContentPro
Android基礎之使用Fragment適應不同屏幕和分辨率(分享)
最近事情很忙,一個新項目趕著出來,但是很多功能都要重新做,一直在編寫代碼、Debug。今天因為一個新程序要使用Fragment來做,雖然以前也使用過Fragment,不過