如何在Android中使用InetAddress获取IPAddress

时间:2017-05-25 13:59:46

标签: java android compiler-errors

我在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

照片: enter image description here

MY VERSION OF JAVA IS JAVA SE 1.6

2 个答案:

答案 0 :(得分:1)

我提出两种选择:

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

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

        public MyClass(...)
        throws UnknownHostException
        {
            this.giriAddress=InetAddress.getByName("www.girionjava.com");
        }
    }

答案 1 :(得分:0)

这是我使用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();
    }
}

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

在这种情况下,您无法在互联网世界中获得任何带有IP地址的主机名,例如“www.girionjava.com”主机。