-1

I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works. The code is the follow:

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

However all time show me:

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

I included the library:

import java.net.InetAddress;

What must I do to use InetAddress in my Android Project?

The class of my project is:

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);
            }
    }

The error's i get.

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

Picture: enter image description here

MY VERSION OF JAVA IS JAVA SE 1.6
user207421
  • 305,947
  • 44
  • 307
  • 483
Sir Jack
  • 227
  • 3
  • 15

2 Answers2

1

I propose two alternatives:

  • If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
    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);
            }
        }
    }
  • But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
    public class MyClass
    {
        private InetAddress giriAddress;

        public MyClass(...)
        throws UnknownHostException
        {
            this.giriAddress=InetAddress.getByName("www.girionjava.com");
        }
    }
Little Santi
  • 8,563
  • 2
  • 18
  • 46
  • Why you create a new subclass in the first class? I did that `public LauncherActivity() { this.giriAddress=InetAddress.getByName("www.girionjava.com");}` however show me this error: `Description Resource Path Location Type Unhandled exception type UnknownHostException LauncherActivity.java //src/my/app/client line 31 Java Problem` – Sir Jack May 25 '17 at 14:57
  • No, it is not a subclass. "MyClass" stands for your class' name, which I didn't know because you didn't post it. – Little Santi May 25 '17 at 15:24
0

This is my simple method using my android application.

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;

}

You can test it with

 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();
    }
}

you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.

This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.

tommybee
  • 2,409
  • 1
  • 20
  • 23