AndroidはネイティブipアドレスとMacアドレスを取得
変換元:http://blog.csdn.net/webdisk008/article/details/6294783
この方法はモトローラマイルストーンでテストに合格した.機能は、ネイティブのIPアドレスとMACアドレスを取得することです.まず新しいプロジェクトを作成し、AndroidManifestを修正します.xmlファイルには、次のようにユーザー権限が追加されます.
変更しますxml、以下のようにします.
主なコードは以下の通り(GetIPMAC.java):
実行効果:
この方法はモトローラマイルストーンでテストに合格した.機能は、ネイティブのIPアドレスとMACアドレスを取得することです.まず新しいプロジェクトを作成し、AndroidManifestを修正します.xmlファイルには、次のようにユーザー権限が追加されます.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
変更しますxml、以下のようにします.
<TextView
android:id ="@+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
主なコードは以下の通り(GetIPMAC.java):
package exp.getipmac;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class GetIPMAC extends Activity {
public static String hostip; // IP
public static String hostmac; // MAC
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv= (TextView)findViewById(R.id.hello);
hostip = getLocalIpAddress(); // IP
hostmac = getLocalMacAddress();// MAC
/* IP MAC */
tv.setText("HostIP:" + hostip + "/nHostMAC:" + hostmac);
/* IP MAC */
if (hostip != null) Log.d("GetIPMAC", hostip);
else Log.d("GetIPMAC", "null");
Log.d("GetIPMAC", hostmac);
}
public String getLocalIpAddress() {
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
}
return null;
}
public String getLocalMacAddress() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
}
実行効果: