reisi007

Airline#getTCPAddress

Jan 15th, 2015
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. /**
  2.      * Gets the TCP Address of this Airline
  3.      *
  4.      * @param ports
  5.      *            Last port is default port
  6.      * @param serverUrl
  7.      *            Url on the server
  8.      * @return The TCP Adress
  9.      */
  10.     private String getTCPAddress(String serverUrl, int... ports) {
  11.         String ip = "127.0.0.1";
  12.         try {
  13.             Enumeration<NetworkInterface> nis = NetworkInterface
  14.                     .getNetworkInterfaces();
  15.             while (nis.hasMoreElements()) {
  16.                 NetworkInterface next = nis.nextElement();
  17.                 Enumeration<InetAddress> add = next.getInetAddresses();
  18.                 while (add.hasMoreElements()) {
  19.                     InetAddress address = add.nextElement();
  20.                     if (!address.isAnyLocalAddress()) {
  21.                         if (address instanceof Inet4Address) {
  22.                             String baseIp = ip = address.getHostAddress();
  23.                             if (!"127.0.0.1".equals(ip)) {
  24.                                 // Guess port
  25.                                 URL url;
  26.                                 for (int p : ports) {
  27.                                     url = new URL("http", baseIp, p, serverUrl);
  28.                                     ip = baseIp + ':' + p;
  29.                                     if (isAvailable(url)) {
  30.                                         return ip;
  31.                                     }
  32.                                 }
  33.                                 return ip;
  34.                             }
  35.                         }
  36.                     }
  37.                 }
  38.             }
  39.             return ip;
  40.         } catch (SocketException | MalformedURLException e) {
  41.             return ip;
  42.         }
  43.     }
  44.     private static int timeout = 3000;
  45.  
  46.     private boolean isAvailable(URL url) {
  47.         try {
  48.             HttpURLConnection connection = (HttpURLConnection) url
  49.                     .openConnection();
  50.             connection.setConnectTimeout(timeout);
  51.             connection.setReadTimeout(timeout);
  52.             connection.setRequestMethod("GET");
  53.             connection.connect();
  54.             int code = connection.getResponseCode();
  55.             return code == HttpURLConnection.HTTP_OK;
  56.         } catch (Exception e) {
  57.             return false;
  58.         }
  59.  
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment