日期:2014-05-20  浏览次数:20819 次

通过IP获取局域网内手机的NetworkInterface时总返回null
现在通过路由器已知手机的ip是192.168.1.100,用这个IP通过下面的代码获得的NetworkInterface总为null。

但是,局域网内运行此代码的台式机的IP为192.168.1.110,用这个IP通过下面的代码获得的NetworkInterface就正常,也能获得对应的MAC地址。请问这是怎么回事?


    public static void main(String[] args) throws Exception
    {
        String ip123 = "192.168.1.";
        boolean found = false;
        
        for (int ip4 = 100; ip4 < 200; ++ip4)
        {
            String curIp = ip123 + ip4;
            NetworkInterface ni;
            
            try
            {
                InetAddress ia = InetAddress.getByName(curIp);
                ni = NetworkInterface.getByInetAddress(ia);
            }
            catch (Exception e)
            {
                System.out.println("IP地址:" + curIp + "非法。");
                continue;
            }

            if (null == ni)
            {
                continue;
            }
            else
            {
                String macStr = "";
                byte[] mac = ni.getHardwareAddress();
                for (int i = 0; i < mac.length; ++i)
                {
                    if (i != 0)
                    {
                        macStr += "-";
                    }
                    
                    //mac[i] & 0xFF 是为了把byte转化为正整数
                    String curMacSection = Integer.toHexString(mac[i] & 0xFF);
                    macStr += curMacSection; 
                }
                
                String targetMac = "5C-E8-EB-BA-F3-D8";
                if (0 == macStr.compareToIgnoreCase(targetMac))
                {
                    //在Windows资源管理器中打开ftp地址。
                    String cmd = "explorer ftp://" + curIp + ":2121";
                    Runtime.getRuntime().exec(cmd);
                    
                    found = true;
                    break;