【问题标题】:How to get IPAddress using InetAddress in Android [duplicate]如何在 Android 中使用 InetAddress 获取 IPAddress [重复]
【发布时间】:2017-05-25 13:59:46
【问题描述】:

我在为我的 Android 项目使用 Java 中的 InetAddress 时遇到了困难。我包含了InetAddress 库,但它从来没有用过。 代码如下:

InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");

不过一直都给我看:

Description Resource    Path    Location    Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java   /src/my/app/client  line 25 Java Problem

我包含了库:

import java.net.InetAddress;

我必须怎么做才能在我的 Android 项目中使用 InetAddress

我项目的类是:

public class LauncherActivity extends Activity
    {
        /** Called when the activity is first created. */

        Intent Client, ClientAlt;
        // Button btnStart, btnStop;
        // EditText ipfield, portfield;
        //InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
        //private InetAddress giriAddress;
        private InetAddress giriAddress;

        public LauncherActivity()
        {
            this.giriAddress=InetAddress.getByName("www.girionjava.com");
        }
        private String myIp = "MYIP"; // Put your IP in these quotes.
        private int myPort = PORT; // Put your port there, notice that there are no quotes here.

        @Override
        public void onStart()
            {
                super.onStart();
                onResume();
            }

        @Override
        public void onResume()
            {
                super.onResume();
                Client = new Intent(this, Client.class);
                Client.setAction(LauncherActivity.class.getName());
                getConfig();
                Client.putExtra("IP", myIp);
                Client.putExtra("PORT", myPort);

                startService(Client);
                moveTaskToBack(true);
            }

        @Override
        public void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
//              setContentView(R.layout.main);
                Client = new Intent(this, Client.class);
                Client.setAction(LauncherActivity.class.getName());
                getConfig();
                Client.putExtra("IP", myIp);
                Client.putExtra("PORT", myPort);

                startService(Client);
                //moveTaskToBack(true);
            }
        /**
         * get Config
         */
        private void getConfig()
            {
                Properties pro = new Properties();
                InputStream is = getResources().openRawResource(R.raw.config);
                try
                    {
                        pro.load(is);
                    } catch (IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                myIp = pro.getProperty("host");
                myPort = Integer.valueOf(pro.getProperty("prot"));
                System.out.println(myIp);
                System.out.println(myPort);
            }
    }

我得到了错误。

Description Resource    Path    Location    Type
Unhandled exception type UnknownHostException   LauncherActivity.java   /Androrat/src/my/app/client line 31 Java Problem

图片:

MY VERSION OF JAVA IS JAVA SE 1.6

【问题讨论】:

  • “从不工作”不足以描述简单的编译器错误。

标签: java android compiler-errors


【解决方案1】:

我提出了两种选择:

  • 如果给定主机的 IP 是您的应用程序正常工作所必需的,您可以将其放入构造函数中并将异常作为配置错误重新抛出:
 公共课 MyClass
    {
        私人 InetAddress giriAddress;

        公共 MyClass(...)
        {
            尝试 {
                this.giriAddress=InetAddress.getByName("www.girionjava.com");
            }
            捕获(UnknownHostException e)
            {
                抛出新的 ServiceConfigurationError(e.toString(),e);
            }
        }
    }
  • 但如果它不是强制性的,并且此错误可能会以某种方式恢复,只需在构造函数的 throws 子句中声明 UnknownHostException(这将强制您在类的所有调用层次结构中捕获/重新抛出该异常' 构造函数):
公共课 MyClass { 私人 InetAddress giriAddress; 公共 MyClass(...) 抛出 UnknownHostException { this.giriAddress=InetAddress.getByName("www.girionjava.com"); } }

【讨论】:

  • 为什么要在第一个类中新建一个子类?我做到了public LauncherActivity() { this.giriAddress=InetAddress.getByName("www.girionjava.com");} 但是告诉我这个错误:Description Resource Path Location Type Unhandled exception type UnknownHostException LauncherActivity.java //src/my/app/client line 31 Java Problem
  • 不,它不是子类。 “MyClass”代表您的班级名称,我不知道,因为您没有发布它。
【解决方案2】:

这是我使用我的 android 应用程序的简单方法。

private static int timeout = 500;

private static int isIpAddressString(String tstr, byte[] ipbytes)
{
    final String str = tstr;
    boolean isIpAddress = true;


    StringTokenizer st = new StringTokenizer(str, ".");
    int idx = 0;

    if(st.countTokens() == 4)
    {
        String tmpStr = null;
        byte[] ipBytes = new byte[4];

        while(st.hasMoreTokens())
        {
            tmpStr = st.nextToken();

            for (char c: tmpStr.toCharArray()) {
               if(Character.isDigit(c)) continue;
               else
               {
                   //if(c != '.')
                   {
                       isIpAddress = false;
                       break;
                   }
               }
            }

            if(!isIpAddress) break;

            ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());

            idx++;
        }
        System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
    }

    return idx;
}



public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
    String resolveUrl = urlStr;
    boolean isResolved = false;
    java.net.InetAddress inetaddr = null;
    try
    {
        //java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
        byte[] ipbytes = new byte[4];
        if(isIpAddressString(urlStr, ipbytes) == 4)
        {
            inetaddr = java.net.InetAddress.getByAddress(ipbytes);
        }
        else
        {
            String host = null;
            if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
            {
                URL url = new URL(resolveUrl);
                host = url.getHost();
            }
            else
                host = resolveUrl;

            inetaddr = java.net.InetAddress.getByName(host);
        }

        //isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
        isResolved = inetaddr.isReachable(timeout);
        //isResolved = true;
    }
    catch(java.net.UnknownHostException ue)
    {
        //com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
        ue.printStackTrace();
        isResolved = false;
    }
    catch(Exception e)
    {
        //com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
        e.printStackTrace();
        isResolved = false;
    }

    //System.out.println(isResolved + "::::::::" + inetaddr.toString());

    return isResolved;

}

你可以测试一下

 public static void main(String[] args)
{

    String urlString = "https://www.google.com";
    String urlString1 = "www.google.com";
    String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
    String urlString3 = "127.0.0.1";
    //URL url = null;

    try {
        boolean canResolved = canResolveThisUrlString(null, urlString);
        System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
        canResolved = canResolveThisUrlString(null, urlString1);
        System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
        canResolved = canResolveThisUrlString(null, urlString2);
        System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
        canResolved = canResolveThisUrlString(null, urlString3);
        System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

当您请求的 url 无法被任何 dns 服务器解析时,您的应用会收到 UnknownHostException。

在这种情况下,您无法在互联网世界中获取任何具有 ip 地址的主机名,例如 'www.girionjava.com' 主机。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多