码迷,mamicode.com
首页 > 移动开发 > 详细

Android中获取本机ip地址和MAC地址

时间:2015-03-29 10:51:02      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:网络   android   

通过InetAddress.getLocalHost()得到始终是“127.0.0.1”,要想得到真正的网络ip地址要通过下面的方法:

首先新建一个工程,修改AndroidManifest.xml文件增加用户权限,如下:

    <uses-permission android:name="android.permission.INTERNET"/>   //必写
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>//必写
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>


主要函数代码如下:

// 得到本机ip地址
    public String getLocalHostIp()
    {
        String ipaddress = "";
        try
        {
            Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements())
            {
                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = nif.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (inet.hasMoreElements())
                {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(ip
                                    .getHostAddress()))
                    {
                        return ipaddress = "本机的ip是" + ":" + ip.getHostAddress();
                    }
                }

            }
        }
        catch (SocketException e)
        {
            Log.e("feige", "获取本地ip地址失败");
            e.printStackTrace();
        }
        return ipaddress;

    }

    // 得到本机Mac地址
    public String getLocalMac()
    {
        String mac = "";
        // 获取wifi管理器
        WifiManager wifiMng = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfor = wifiMng.getConnectionInfo();
        mac = "本机的mac地址是:" + wifiInfor.getMacAddress();
        return mac;
    }

Android中获取本机ip地址和MAC地址

标签:网络   android   

原文地址:http://blog.csdn.net/xiaole0313/article/details/44724835

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!