||
/** * 獲取本地 ip *@return */ public String getLocalIpAddress(){ try{ String ipv4=null; // 取得機器所有網路介面 List<NetworkInterface> nilist= Collections.list(NetworkInterface.getNetworkInterfaces()); for(NetworkInterface ni:nilist){ // 取得網卡所有的 IP 地址 List<InetAddress>ialist=Collections.list(ni.getInetAddresses()); for(InetAddress address:ialist){ // 只取 IPv4 地址 ipv4=address.getHostAddress(); if(!address.isLoopbackAddress() && address instanceof Inet4Address){ return ipv4; } } } }catch(SocketException ex){ Log.e(TAG, ex.toString()); } return"0.0.0.0"; } /** *通過本地 ip 獲取 mac 地址 *通過 ip 獲取的 mac 地址, 所以當是 wifi 連線時的 ip 獲取到的則是 WIFI 的 mac,如果是*Ethernet 連線時則獲取的是 Ethernet 的 mac 地址 *@return */ public String getLocalMacAddressFromIp(){ String mac_s=""; try{ byte[]mac; // 獲取本地 IP String ip=getLocalIpAddress(); // 取得網卡 InetAddress ipAddress=InetAddress.getByName(ip); if(ipAddress==null){ return mac_s; } // 只取 IPv4 地址 if(!(ipAddress instanceof Inet4Address)){ return mac_s; } // 取 MAC NetworkInterface ne=NetworkInterface.getByInetAddress(ipAddress); mac=ne.getHardwareAddress(); if(mac.length>0){ mac_s=byte2mac(mac); } }catch(Exception e){ e.printStackTrace(); }finally{ return mac_s; } } // 轉為 MAC 文字 private String byte2mac(byte[]b){ StringBuffer hs=new StringBuffer(b.length); String stmp=""; int len=b.length; for(int n=0;n<len;n++){ stmp=Integer.toHexString(b[n]&0xFF); if(stmp.length()==1){ hs=hs.append("0").append(stmp); }else{ hs=hs.append(stmp); } } StringBuffer str=new StringBuffer(hs); for(int i=0;i<str.length();i++){ if(i%3==0){ str.insert(i,":"); } } return str.toString().substring(1); } /** *獲取 Ethernet 的 MAC 地址 *@return */ private String getWireMac(){ String strMacAddress = null; try { // 取得網卡 MAC byte[] b = NetworkInterface.getByName("eth0") .getHardwareAddress(); strMacAddress = byte2mac(b); } catch (Exception e) { e.printStackTrace(); } return strMacAddress; } /** *獲取 wifi mac *@return */ private String getWifiMac(){ WifiManager wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE); WifiInfo info=wifi.getConnectionInfo(); return info.getMacAddress()==null?"":info.getMacAddress(); } |