Android 在wifi下获取IP和MAC地址
Button
02 android:id="@+id/btn"
03 android:text="获取IP"
04 android:layout_width="fill_parent"
05 android:layout_height="wrap_content"
06 android:onClick="onclick"
07 />
08 <EditText
09 android:id="@+id/ip_txt"
10 android:layout_width="fill_parent"
11 android:layout_height="wrap_content"/>
12
13 <EditText
14 android:id="@+id/mac_txt"
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"/>
//这里是权限
1 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
2 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
//接下来就是正文
01 package com.wifi;
02
03 import java.net.InetAddress;
04 import java.net.NetworkInte易做图ce;
05 import java.net.SocketException;
06 import java.util.Enumeration;
07
08 import android.app.Activity;
09 import android.content.Context;
10 import android.net.wifi.WifiInfo;
11 import android.net.wifi.WifiManager;
12 import android.os.Bundle;
13 import android.util.Log;
14 import android.view.View;
15 import android.widget.Button;
16 import android.widget.EditText;
17 public class MainActivity extends Activity {
18 public static String IP; //本机IP
19 public static String MAC; //本机MAC
20
21 Button btn=null;
22 EditText ip_txt=null;
23 EditText mac_txt=null;
24 @Override
25 public void onCreate(Bundle savedInstanceState) {
26 super.onCreate(savedInstanceState);
27 setContentView(R.layout.main);
28 btn=(Button)findViewById(R.id.btn);
29 ip_txt=(EditText)findViewById(R.id.ip_txt);
30 mac_txt=(EditText)findViewById(R.id.mac_txt);
31
32 }
33 public void onclick(View v){
34 switch (v.getId()) {
35 case R.id.btn:
36 IP = getLocalIpAddress(); //获取本机IP
37 MAC = getLocalMacAddress();//获取本机MAC
38 ip_txt.setText(IP);
39 mac_txt.setText(MAC);
40 break;
41 }
42 }
43
44 public String getLocalIpAddress() {
45 try {
46 for (Enumeration<NetworkInte易做图ce> en = NetworkInte易做图ce
47 .getNetworkInte易做图ces(); en.hasMoreElements();) {
48 NetworkInte易做图ce intf = en.nextElement();
49 for (Enumeration<InetAddress> enumIpAddr = intf
50 .getInetAddresses(); enumIpAddr.hasMoreElements();) {
51 InetAddress inetAddress = enumIpAddr.nextElement();
52 if (!inetAddress.isLoopbackAddress()) {
53 return inetAddress.getHostAddress().toString();
54 }
55 }
56 }
57 } catch (SocketException ex) {
58 Log.e("WifiPreference IpAddress", ex.toString());
59 }
60 return null;
61 }
62
63 public String getLocalMacAddress() {
64 WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
65 WifiInfo info = wifi.getConnectionInfo();
66 return info.getMacAddress();
67 }
68 }
补充:移动开发 , Android ,