Android 获取本机Ip 和 Mac

来源:互联网 发布:服务器端编程心得 编辑:程序博客网 时间:2024/05/17 07:37

 

 

获取本机IP和MAC。

 

public class MainActivity extends Activity {private EditText ed1, ed2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ed1 = (EditText) findViewById(R.id.et1);ed2 = (EditText) findViewById(R.id.et2);ed1.setText(getIP());ed2.setText(getLocalMacAddressFromIp(getIP()));new Thread() {@Overridepublic void run() {try {sendInfo();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}.start();}public void sendInfo() throws Exception {//可以通过 DatagramPacket 的getAddress()方法获取ipfinal String GROUP_ADDR = "224.224.224.224";final int PORT = 4444;MulticastSocket ms = new MulticastSocket(PORT);InetAddress addr = InetAddress.getByName(GROUP_ADDR);ms.joinGroup(addr);String info = "hello";byte[] buf = info.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, addr, PORT);while (true) {Thread.sleep(2000);ms.send(dp);}}public static String getIP() {try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()&& !inetAddress.isLinkLocalAddress()) {return inetAddress.getHostAddress().toString();}}}} catch (Exception e) {e.printStackTrace();}return null;}public static String getLocalMacAddressFromIp(String ipStr){String mac_s = "";try {byte[] mac;NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(ipStr));mac = ne.getHardwareAddress();mac_s = byte2hex(mac);} catch (Exception e) {e.printStackTrace();}return mac_s;}public static String byte2hex(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);}}return String.valueOf(hs);}


 

 参考资料:

http://blog.sina.com.cn/s/blog_77c632410101cy1v.html

 

 

 

0 0
原创粉丝点击