【问题标题】:InetAddress Ip address lookup from hostname AndroidInetAddress 从主机名查找 IP 地址 Android
【发布时间】:2015-04-10 11:04:25
【问题描述】:

我正在尝试使用 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]

【问题讨论】:

  • “不起作用”以什么方式?它会崩溃吗?它没有显示IP地址吗? ...
  • “很遗憾 App_mobile 已停止”
  • 我是通过手机而不是模拟器测试的
  • 然后logcat会告诉你它为什么会崩溃。请张贴相关部分。

标签: android android-asynctask dns hostname inetaddress


【解决方案1】:

return addr.getHostAddress();。即使在捕获之后你使用addr 但它是null 然后你有一个NullPointerException。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2014-04-27
    • 2016-01-21
    • 2014-02-15
    相关资源
    最近更新 更多