Пример #1
0
  // function to do the join use case
  public static void share() throws Exception {
    HttpPost method = new HttpPost(url + "/share");
    String ipAddress = null;

    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) en.nextElement();
      if (ni.getName().equals("eth0")) {
        Enumeration<InetAddress> en2 = ni.getInetAddresses();
        while (en2.hasMoreElements()) {
          InetAddress ip = (InetAddress) en2.nextElement();
          if (ip instanceof Inet4Address) {
            ipAddress = ip.getHostAddress();
            break;
          }
        }
        break;
      }
    }

    method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8"));
    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    // get present time
    date = new Date();
    long start = date.getTime();

    // Execute the vishwa share process
    Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp);

    String ch = "alive";
    System.out.println("Type kill to unjoin from the grid");

    while (!ch.equals("kill")) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      ch = in.readLine();
    }

    p.destroy();

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/shareAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
Пример #2
0
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
 static String serverAddresses() throws SocketException {
   String ipaddrs = "127.0.0.1";
   NetworkInterface ni = NetworkInterface.getByName("en0");
   if (ni != null)
     for (Enumeration<InetAddress> e = ni.getInetAddresses(); e.hasMoreElements(); )
       ipaddrs += "  " + e.nextElement().getHostAddress();
   return ipaddrs; // should return space separated ip addresses serverSocket is listening on
 }
  /**
   * Returns an InetAddress instance that represents the localhost, and that a socket can bind upon
   * or distribute to peers as a contact address.
   *
   * @param intendedDestination the destination that we'd like to use the localhost address with.
   * @return an InetAddress instance representing the local host, and that a socket can bind upon or
   *     distribute to peers as a contact address.
   */
  public synchronized InetAddress getLocalHost(InetAddress intendedDestination) {
    // no point in making sure that the localHostFinderSocket is initialized.
    // better let it through a NullPointerException.
    InetAddress localHost = null;
    localHostFinderSocket.connect(intendedDestination, this.RANDOM_ADDR_DISC_PORT);
    localHost = localHostFinderSocket.getLocalAddress();
    localHostFinderSocket.disconnect();
    // windows socket implementations return the any address so we need to
    // find something else here ... InetAddress.getLocalHost seems to work
    // better on windows so lets hope it'll do the trick.
    if (localHost.isAnyLocalAddress()) {
      try {
        // all that's inside the if is an ugly IPv6 hack
        // (good ol' IPv6 - always causing more problems than it solves.)
        if (intendedDestination instanceof Inet6Address) {
          // return the first globally routable ipv6 address we find
          // on the machine (and hope it's a good one)
          Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

          while (interfaces.hasMoreElements()) {
            NetworkInterface iface = (NetworkInterface) interfaces.nextElement();
            Enumeration addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
              InetAddress address = (InetAddress) addresses.nextElement();
              if (address instanceof Inet6Address) {
                if (!address.isAnyLocalAddress()
                    && !address.isLinkLocalAddress()
                    && !address.isSiteLocalAddress()
                    && !address.isLoopbackAddress()) {
                  return address;
                }
              }
            }
          }
        } else localHost = InetAddress.getLocalHost();
        /** @todo test on windows for ipv6 cases */
      } catch (Exception ex) {
        // sigh ... ok return 0.0.0.0
        logger.warn("Failed to get localhost ", ex);
      }
    }

    return localHost;
  }
Пример #5
0
 static void displayInfo(NetworkInterface netint) throws IOException {
   inetAddresses = netint.getInterfaceAddresses();
   System.out.println("some information about my link:");
   System.out.printf("Display name: %s\n", netint.getDisplayName());
   System.out.printf("Name: %s\n", netint.getName());
   System.out.printf("Up? %s\n", netint.isUp());
   System.out.printf("Loopback? %s\n", netint.isLoopback());
   System.out.printf("PointToPoint? %s\n", netint.isPointToPoint());
   System.out.printf("Supports multicast? %s\n", netint.supportsMulticast());
   System.out.printf("Virtual? %s\n", netint.isVirtual());
   System.out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress()));
   System.out.printf("MTU: %s\n", netint.getMTU());
   System.out.printf("\n");
   System.out.println(
       "my ip address is: " + ((InterfaceAddress) inetAddresses.get(0)).getAddress());
   System.out.println(
       "the sunnetmask address is: "
           + ((InterfaceAddress) inetAddresses.get(0)).getNetworkPrefixLength());
   System.out.println("the broadcast address of this subnet is:" + bcid);
 }
 public String getLocalIpAddress() {
   try {
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
         en.hasMoreElements(); ) {
       NetworkInterface intf = en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
           enumIpAddr.hasMoreElements(); ) {
         InetAddress inetAddress = enumIpAddr.nextElement();
         // if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() &&
         // inetAddress.isSiteLocalAddress() ) {
         if (!inetAddress.isLoopbackAddress()
             && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
           String ipAddr = inetAddress.getHostAddress();
           return ipAddr;
         }
       }
     }
   } catch (SocketException ex) {
     Log.d(TAG, ex.toString());
   }
   return null;
 }
Пример #7
0
 public static void main(String[] args) {
   try {
     Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
     for (NetworkInterface netint : Collections.list(nets)) displayInfo(netint);
     pinging();
   } catch (java.net.SocketException s) {
     System.out.print('/'); //
     System.exit(0);
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
 }
 @PostConstruct
 public void getHostAdderesAndConnectToMS() {
   try {
     Enumeration e = NetworkInterface.getNetworkInterfaces();
     while (e.hasMoreElements()) {
       NetworkInterface n = (NetworkInterface) e.nextElement();
       Enumeration ee = n.getInetAddresses();
       while (ee.hasMoreElements()) {
         InetAddress i = (InetAddress) ee.nextElement();
         if (i.getHostAddress().contains("10.") || i.getHostAddress().contains("192.")) {
           hostAdder = i.getHostAddress().trim();
           System.out.println("Run at start. IP:" + hostAdder);
           if (masterService.connectPS(hostAdder) == FAILED) {
             System.out.println("Could not connect to MS. Shutting down");
             System.exit(0);
           }
           return;
         }
       }
     }
   } catch (Exception e) {
   }
 }
Пример #9
0
 public static void showNIC() {
   // http://www.informatik-blog.net/2009/01/28/informationen-der-netzwerkkarten-auslesen/
   try {
     Enumeration<NetworkInterface> interfaceNIC = NetworkInterface.getNetworkInterfaces();
     // Alle Schnittstellen durchlaufen
     while (interfaceNIC.hasMoreElements()) {
       // Elemente abfragen und ausgeben
       NetworkInterface n = interfaceNIC.nextElement();
       System.out.println(
           String.format("Netzwerk-Interface: %s (%s)", n.getName(), n.getDisplayName()));
       // Adressen abrufen
       Enumeration<InetAddress> addresses = n.getInetAddresses();
       // Adressen durchlaufen
       while (addresses.hasMoreElements()) {
         InetAddress address = addresses.nextElement();
         System.out.println(String.format("- %s", address.getHostAddress()));
       }
     }
     System.out.println();
   } catch (SocketException e) {
     e.printStackTrace();
   }
 }
Пример #10
0
  /** @return */
  public static String getIPv4Address() {
    String ipv4address = null;

    try {
      final List<NetworkInterface> networkinterfaces =
          Collections.list(NetworkInterface.getNetworkInterfaces());
      for (final NetworkInterface networkinterface : networkinterfaces) {
        final List<InetAddress> addresses = Collections.list(networkinterface.getInetAddresses());
        for (final InetAddress address : addresses) {
          if ((address == null) || address.isLoopbackAddress()) {
            continue;
          }
          if (address instanceof Inet4Address) {
            ipv4address = address.getHostAddress().toString();
            break;
          }
        }
      }
    } catch (Exception x) {
      DBG.m(x);
    }

    return ipv4address;
  }
Пример #11
0
 /**
  * Get IP address from first non-localhost interface
  *
  * @param ipv4 true=return ipv4, false=return ipv6
  * @return address or empty string
  */
 public static String getIPAddress(boolean useIPv4) {
   try {
     List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
     for (NetworkInterface intf : interfaces) {
       List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
       for (InetAddress addr : addrs) {
         if (!addr.isLoopbackAddress()) {
           String sAddr = addr.getHostAddress().toUpperCase();
           boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
           if (useIPv4) {
             if (isIPv4) return sAddr;
           } else {
             if (!isIPv4) {
               int delim = sAddr.indexOf('%'); // drop ip6 port suffix
               return delim < 0 ? sAddr : sAddr.substring(0, delim);
             }
           }
         }
       }
     }
   } catch (Exception ex) {
   } // for now eat exceptions
   return "";
 }
 /**
  * Discover WS device on the local network
  *
  * @return list of unique devices access strings which might be URLs in most cases
  */
 public static Collection<String> discoverWsDevices() {
   final Collection<String> addresses = new ConcurrentSkipListSet<>();
   final CountDownLatch serverStarted = new CountDownLatch(1);
   final CountDownLatch serverFinished = new CountDownLatch(1);
   final Collection<InetAddress> addressList = new ArrayList<>();
   try {
     final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
     if (interfaces != null) {
       while (interfaces.hasMoreElements()) {
         NetworkInterface anInterface = interfaces.nextElement();
         if (!anInterface.isLoopback()) {
           final List<InterfaceAddress> interfaceAddresses = anInterface.getInterfaceAddresses();
           for (InterfaceAddress address : interfaceAddresses) {
             addressList.add(address.getAddress());
           }
         }
       }
     }
   } catch (SocketException e) {
     e.printStackTrace();
   }
   ExecutorService executorService = Executors.newCachedThreadPool();
   for (final InetAddress address : addressList) {
     Runnable runnable =
         new Runnable() {
           public void run() {
             try {
               final String uuid = UUID.randomUUID().toString();
               final String probe =
                   WS_DISCOVERY_PROBE_MESSAGE.replaceAll(
                       "<wsa:MessageID>urn:uuid:.*</wsa:MessageID>",
                       "<wsa:MessageID>urn:uuid:" + uuid + "</wsa:MessageID>");
               final int port = random.nextInt(20000) + 40000;
               @SuppressWarnings("SocketOpenedButNotSafelyClosed")
               final DatagramSocket server = new DatagramSocket(port, address);
               new Thread() {
                 public void run() {
                   try {
                     final DatagramPacket packet = new DatagramPacket(new byte[4096], 4096);
                     server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
                     long timerStarted = System.currentTimeMillis();
                     while (System.currentTimeMillis() - timerStarted < (WS_DISCOVERY_TIMEOUT)) {
                       serverStarted.countDown();
                       server.receive(packet);
                       final Collection<String> collection =
                           parseSoapResponseForUrls(
                               Arrays.copyOf(packet.getData(), packet.getLength()));
                       for (String key : collection) {
                         addresses.add(key);
                       }
                     }
                   } catch (SocketTimeoutException ignored) {
                   } catch (Exception e) {
                     e.printStackTrace();
                   } finally {
                     serverFinished.countDown();
                     server.close();
                   }
                 }
               }.start();
               try {
                 serverStarted.await(1000, TimeUnit.MILLISECONDS);
               } catch (InterruptedException e) {
                 e.printStackTrace();
               }
               if (address instanceof Inet4Address) {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
                         WS_DISCOVERY_PORT));
               } else {
                 server.send(
                     new DatagramPacket(
                         probe.getBytes(),
                         probe.length(),
                         InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6),
                         WS_DISCOVERY_PORT));
               }
             } catch (Exception e) {
               e.printStackTrace();
             }
             try {
               serverFinished.await((WS_DISCOVERY_TIMEOUT), TimeUnit.MILLISECONDS);
             } catch (InterruptedException e) {
               e.printStackTrace();
             }
           }
         };
     executorService.submit(runnable);
   }
   try {
     executorService.shutdown();
     executorService.awaitTermination(WS_DISCOVERY_TIMEOUT + 2000, TimeUnit.MILLISECONDS);
   } catch (InterruptedException ignored) {
   }
   return addresses;
 }
Пример #13
0
  public void run() {
    try {
      this.serverSocket = new ServerSocket(Settings.getPropertyInteger("server_port"));
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_open_port_", Settings.getLocale())
              + Settings.getPropertyInteger("server_port"));
      if (FancyFileServer.getGUI() != null) {
        FancyFileServer.getGUI().updateServerStatus();
      }
      return;
    }

    running = true;

    this.parameters = new BasicHttpParams();
    this.parameters.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000);
    this.parameters.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    this.parameters.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    this.parameters.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true);
    this.parameters.setParameter(
        HttpProtocolParams.ORIGIN_SERVER,
        FancyFileServer.NAME.replaceAll("\\s", "-") + "/" + FancyFileServer.VERSION);

    Logger.log(Level.INFO, Messages.getString("server_started", Settings.getLocale()));

    try {
      Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) interfaces.nextElement();
        if (i.isLoopback() || i.isVirtual()) {
          continue;
        }
        Enumeration<InetAddress> addresses = i.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress a = (InetAddress) addresses.nextElement();
          if (a instanceof Inet4Address) {
            Logger.log(
                Level.INFO,
                Messages.getString("server_address_", Settings.getLocale())
                    + "http://"
                    + a.getHostAddress()
                    + ":"
                    + serverSocket.getLocalPort()
                    + "/");
          }
        }
      }
    } catch (Exception e) {
      Logger.log(
          Level.WARNING,
          Messages.getString("can_not_get_server_address_", Settings.getLocale()) + e.getMessage());
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }

    while (running) {
      try {
        /** Set up HTTP connection */
        Socket socket = this.serverSocket.accept();
        DefaultHttpServerConnection connection = new DefaultHttpServerConnection();
        Logger.log(
            Level.DEBUG,
            Messages.getString("incoming_connection_from_", Settings.getLocale())
                + socket.getInetAddress().getHostAddress());
        connection.bind(socket, this.parameters);

        /** Set up HTTP protocol processor */
        BasicHttpProcessor processor = new BasicHttpProcessor();
        processor.addInterceptor(new ResponseDate());
        processor.addInterceptor(new ResponseServer());
        processor.addInterceptor(new ResponseContent());
        processor.addInterceptor(new ResponseConnControl());

        /** Set up HTTP request handlers */
        HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
        registry.register("*", new FileHandler());

        /** Set up HTTP service */
        HttpService service =
            new HttpService(
                processor,
                new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory(),
                registry,
                this.parameters);

        /** Start worker thread */
        WorkerThread t = new WorkerThread(this, service, connection);
        t.setDaemon(true);
        t.start();
      } catch (IOException e) {
        if (running) {
          running = false;
          Logger.log(
              Level.SEVERE,
              Messages.getString("i_o_error_", Settings.getLocale()) + e.getMessage());
          break;
        }
      }
    }

    if (FancyFileServer.getGUI() != null) {
      FancyFileServer.getGUI().updateServerStatus();
    }
    Logger.log(Level.INFO, Messages.getString("server_stopped", Settings.getLocale()));
  }