之前一直以為只要列舉NetworkInterface即可,結果在HTㄈ的手機上面踢到鐵板。 該死的HTㄈ的部分機種在3G數據關閉的時候還是會給我3G的ip,又讓我更討厭了HTㄈ一點。
查了網路才知道還有另一個獲得wifi的ip位址的方法,在這邊紀錄一下。
2014/11/17 追記: 因為有部分的手機會自己偷偷加一個ipv4地址給usb用(如小米),
必須找出一個可以確認ip真的是可用ip的方法。
經過觀察,3g的ip也會有ipv6的位址,所以可以使用此法判斷。
本來想使用network interface name判斷,但是發現emulator的interfce name不是標準的「rmnet_usbX」,
無法使用此法。
try {
//added by chacha 20121217 for wifi address should use this method to get.
WifiManager wifiMan = (WifiManager) (AppFocused.getCurrentContext().getSystemService(Context.WIFI_SERVICE));
WifiInfo wifiInf = wifiMan.getConnectionInfo();
long ip = wifiInf.getIpAddress();
if( ip != 0 )
return String.format( "%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
//added by chacha 20121217 for wifi address should use this method to get.
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
List addrs = Collections.list(intf.getInetAddresses());
{
String strIPV4Addr = "";
boolean hasIPV6 = false;
for (InetAddress addr : addrs)
{
if (!addr.isLoopbackAddress())
{
String sAddr = addr.getHostAddress();
if (addr instanceof Inet4Address)
strIPV4Addr = sAddr;
else if (addr instanceof Inet6Address)
hasIPV6 = true;
}
}
if (hasIPV6 && (strIPV4Addr.length() > 0))
{
if (BuildConfig.DEBUG) Log.d("chacha", "inet addr= " + strIPV4Addr);
return strIPV4Addr;
}
}
}
}
catch (Exception e)
{
return null;
}
return null;
0 件のコメント:
コメントを投稿