来自主机名Android的InetAddress IP地址查找

时间:2015-04-10 11:04:25

标签: android android-asynctask dns hostname inetaddress

我正在尝试使用InetAddress从Android应用程序中获取其主机名的计算机(或Raspberry Pi)的IP地址,问题是当我键入“www.google.com”时,例如它有效,但是当我尝试“PC ****”这是我的PC主机名(从cmd命令主机名获取)它不起作用 请帮帮我

 public void SearchMachines(View v) {
     String netAddress = null;
     TextView localTextView = (TextView)findViewById(R.id.tvScaned);
     try
      {
       netAddress = new NetTask().execute("www.google.com").get();
       localTextView.setText("Address: " + netAddress);
      }
      catch (Exception e1)
       {
        e1.printStackTrace();
       }


 }
 public class NetTask extends AsyncTask<String, Integer, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            InetAddress addr = null;
            try
            {
                addr = InetAddress.getByName(params[0]);
            }

            catch (UnknownHostException e)
            {
                            e.printStackTrace();
            }
            return addr.getHostAddress();
        }
    }
 ![Here is Logcat][1]

1 个答案:

答案 0 :(得分:0)

return addr.getHostAddress();。即使在捕获后您使用的是addr,但它是null,因此您拥有NullPointerException

将该语句放在try块中,并将return e.getMessage();放入catch块。