2015年4月28日 星期二

[Android] Determine if IP is reachable using HTTP or Sockets

In my App,  I need to determine if a specific address is reachable. I find that there are 2 mainstream methods of accomplishing this. The first the the HttpGet method and the second is the Socket method.



Below are the code snippets for both methods with retry timeouts
Reminder that when using this method, the url that is passed into this function must contain "http://" header. For example if I were to check if 192.168.1.10 is online, I would use this function as isReachable_http("http://192.168.1.10");
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 public boolean isReachable_http(String url) throws Exception {
   HttpGet httpGet = new HttpGet(url);
   HttpParams httpParameters = new BasicHttpParams();
   int timeoutConnection = 2000;  //retry for 2 seconds
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   HttpResponse httpResp = httpClient.execute(httpGet);
  
   // if connect success , true
   if (httpResp.getStatusLine().getStatusCode() == 200)
     return true;
   else 
     return false;
   
 }


When using the socket method, the url must not contain "http://" header. To use this function, execute isReachable_socket("192.168.1.10");

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public boolean isReachable_socket(String url, int port) throws Exception {
  boolean reachable = false;
  try {
      Socket socket = new Socket(url, port);
      reachable = true;
  } finally {          
      if (socket != null) try { socket.close(); } catch(IOException e) {}
  }
  return reachable;
 }
If you use a http:// header when using sockets, you will see error message such as:
java.net.unknownhostexception unable to resolve host:"http://192.168.1.10", no address associated with hostname

沒有留言:

張貼留言