Question

I have an issue were if I try to InetAddress.getLocalHost() or even InetAddress.getByName(String host) it throws an exception every time even for a known website like nba.com I am a bit confused FYI the target device is an android 4.1.1 GS3 and wifi and mobile network are on. Code below

         try{
        InetAddress ownIP=InetAddress.getLocalHost();
        System.out.println("IP of my Android := "+ownIP.getHostAddress());
        }catch (Exception e){
            System.out.println("Exception caught ="+e.getMessage());
            String t =  e.getMessage() + "yes";
        }

Below is the System.out

03-12 18:59:52.636: I/System.out(18996): Exception caught =null

Thanks in advance

Was it helpful?

Solution 2

I believe I have found out what my issue was basically I guess you are not allowed to perform any network operations in the Main thread for android this was optional before and is now required for Honeycomb (API 11) and up below is the comment as per google specs.

"To prevent blocking the main user interface thread, Google recommends using the AsyncTask class from the android.os package:"

So all I was create a new class NetTask which extends AsyncTask and perform all network applications so now my code is working. IDK if everybody else knew that but I figured I would post this in case any newbs like me were still looking for a solution :) !!!

Thanks

OTHER TIPS

I use a tricky method to get my own IP. you can see whether it helps you

String getIP() {
    try {
        Socket socket = new Socket("google.com", 80);
        return socket.getLocalAddress().getHostAddress();
    } catch (Exception e) {

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top