綁定帳號登入

Android 台灣中文網

tag 標籤: 和

相關日誌

分享 Android 學習:獲取 Ethernet、WIFI 的 ip 和 mac 地址
jianrupan 2021-8-5 14:57
/** * 獲取本地 ip *@return */ public String getLocalIpAddress(){ try{ String ipv4=null; // 取得機器所有網路介面 ListNetworkInterface nilist= Collections.list(NetworkInterface. getNetworkInterfaces ()); for(NetworkInterface ni:nilist){ // 取得網卡所有的 IP 地址 ListInetAddressialist=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 b){ StringBuffer hs=new StringBuffer(b.length); String stmp=""; int len=b.length; for(int n=0;nlen;n++){ stmp=Integer.toHexString(b 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;istr.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(); }
個人分類: 軟體應用|336 次閱讀|0 個評論