android下擷取mac ip

來源:互聯網
上載者:User

/**

* 在wifi未開啟狀態下,仍然可以擷取MAC地址,但是IP地址必須在已串連狀態下否則為0

* @param context

*/

public
static void getMacAddress(Context context) {

String macAddress =
null, ip = null;

WifiManager wifiMgr = (WifiManager) context

.getSystemService(Context.WIFI_SERVICE);

WifiInfo info = (null == wifiMgr ?
null : wifiMgr.getConnectionInfo());

if (null != info) {

macAddress = info.getMacAddress();

//
ip = int2ip(info.getIpAddress());

}

System.out.println("mac:" + macAddress +
",ip:" + ip);

}

/**

* 原理:IP地址每段可以看成是8位不帶正負號的整數即0-255,把每段拆分成一個二進位形式組合起來,然後把這個位元轉變成 一個無符號32為整數。

* 舉例:一個ip地址為10.0.3.193 每段數字 相對應的位元 10 00001010 0 00000000 3 00000011 193

* 11000001 組合起來即為:00001010 00000000 00000011

* 11000001,轉換為10進位就是:167773121,即該IP地址轉換後的數字就是它了

* @param ip

* @return

*/

public
static long ip2int(String ip) {

String[] items = ip.split("\\.");

return Long.valueOf(items[0]) << 24 | Long.valueOf(items[1]) << 16

| Long.valueOf(items[2]) << 8 | Long.valueOf(items[3]);

}

/**

* 原理:把這個整數轉換成一個32位位元。從左至右,每8位進行一下分割,得到4段8位的位元,把這些位元轉換成整數然後加上”.”

* 就是這個ip地址了 舉例:167773121 二進位表示形式為:00001010 00000000 00000011 11000001

* 分割成四段:00001010,00001010,00000011,11000001,分別轉換為整數後加上“.”就得到了10.0.3.193

* @param ipInt

* @return

*/

public
static String int2ip(long ipInt) {

StringBuilder sb =
new StringBuilder();

sb.append(ipInt & 0xFF).append(".");

sb.append((ipInt >> 8) & 0xFF).append(".");

sb.append((ipInt >> 16) & 0xFF).append(".");

sb.append((ipInt >> 24) & 0xFF);

return sb.toString();

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.