Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Gets the TCP Address of this Airline
- *
- * @param ports
- * Last port is default port
- * @param serverUrl
- * Url on the server
- * @return The TCP Adress
- */
- private String getTCPAddress(String serverUrl, int... ports) {
- String ip = "127.0.0.1";
- try {
- Enumeration<NetworkInterface> nis = NetworkInterface
- .getNetworkInterfaces();
- while (nis.hasMoreElements()) {
- NetworkInterface next = nis.nextElement();
- Enumeration<InetAddress> add = next.getInetAddresses();
- while (add.hasMoreElements()) {
- InetAddress address = add.nextElement();
- if (!address.isAnyLocalAddress()) {
- if (address instanceof Inet4Address) {
- String baseIp = ip = address.getHostAddress();
- if (!"127.0.0.1".equals(ip)) {
- // Guess port
- URL url;
- for (int p : ports) {
- url = new URL("http", baseIp, p, serverUrl);
- ip = baseIp + ':' + p;
- if (isAvailable(url)) {
- return ip;
- }
- }
- return ip;
- }
- }
- }
- }
- }
- return ip;
- } catch (SocketException | MalformedURLException e) {
- return ip;
- }
- }
- private static int timeout = 3000;
- private boolean isAvailable(URL url) {
- try {
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
- connection.setConnectTimeout(timeout);
- connection.setReadTimeout(timeout);
- connection.setRequestMethod("GET");
- connection.connect();
- int code = connection.getResponseCode();
- return code == HttpURLConnection.HTTP_OK;
- } catch (Exception e) {
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment