コード例 #1
1
ファイル: JolokiaServer.java プロジェクト: rhuss/jolokia
  private String detectAgentUrl(
      HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) {
    serverAddress = pServer.getAddress();
    InetAddress realAddress;
    int port;
    if (serverAddress != null) {
      realAddress = serverAddress.getAddress();
      if (realAddress.isAnyLocalAddress()) {
        try {
          realAddress = NetworkUtil.getLocalAddress();
        } catch (IOException e) {
          try {
            realAddress = InetAddress.getLocalHost();
          } catch (UnknownHostException e1) {
            // Ok, ok. We take the original one
            realAddress = serverAddress.getAddress();
          }
        }
      }
      port = serverAddress.getPort();
    } else {
      realAddress = pConfig.getAddress();
      port = pConfig.getPort();
    }

    return String.format(
        "%s://%s:%d%s", pConfig.getProtocol(), realAddress.getHostAddress(), port, pContextPath);
  }
コード例 #2
0
 public static boolean isServer() throws Exception {
   boolean isServer = false;
   InetAddress IP = InetAddress.getLocalHost();
   try {
     if (IP.getHostAddress().toString().equals("54.186.249.201")
         || IP.getHostAddress().toString().equals("172.31.40.246")
         || IP.getHostAddress().toString().equals("128.199.237.142")
         || IP.getHostAddress().toString().equals("saracourierservice.tk")) {
       isServer = true;
     }
   } catch (Exception ex) {
     throw ex;
   }
   return isServer;
 }
コード例 #3
0
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
  // 获得IP地址
  public static String getIpAddr(HttpServletRequest request) {
    String ipAddress = null;
    ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getRemoteAddr();
      if (ipAddress.equals("127.0.0.1")) {
        // 根据网卡取本机配置的IP
        InetAddress inet = null;
        try {
          inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }
        ipAddress = inet.getHostAddress();
      }
    }

    // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
      // = 15
      if (ipAddress.indexOf(",") > 0) {
        ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
      }
    }
    return ipAddress;
  }
コード例 #4
0
ファイル: TRTrackerUtils.java プロジェクト: aprasa/oldwork
  static void readConfig() {
    tracker_ip = COConfigurationManager.getStringParameter("Tracker IP", "");

    tracker_ip = UrlUtils.expandIPV6Host(tracker_ip);

    String override_ips = COConfigurationManager.getStringParameter("Override Ip", "");

    StringTokenizer tok = new StringTokenizer(override_ips, ";");

    Map new_override_map = new HashMap();

    while (tok.hasMoreTokens()) {

      String ip = tok.nextToken().trim();

      if (ip.length() > 0) {

        new_override_map.put(AENetworkClassifier.categoriseAddress(ip), ip);
      }
    }

    override_map = new_override_map;

    InetAddress bad = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

    if (bad == null || bad.isAnyLocalAddress()) {

      bind_ip = "";

    } else {

      bind_ip = bad.getHostAddress();
    }
  }
コード例 #5
0
ファイル: Client.java プロジェクト: pksunkara/c3
  // 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();
    }
  }
コード例 #6
0
  /** Creates the server. */
  public static void main(String args[]) {
    client = null;
    ServerSocket server = null;

    try {
      System.out.print("\nCreating Server...\n");
      // creates the server
      server = new ServerSocket(8008);
      System.out.print("Created\n");
      // get the ip Address and the host name.
      InetAddress localAddr = InetAddress.getLocalHost();
      System.out.println("IP address: " + localAddr.getHostAddress());
      System.out.println("Hostname: " + localAddr.getHostName());

    } catch (IOException e) {
      // sends a
      System.out.println("IO" + e);
    }

    // constantly checks for a new aocket trying to attach itself to the trhead
    while (true) {
      try {
        client = server.accept();
        // create a new thread.
        FinalMultiThread thr = new FinalMultiThread(client);
        System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n");
        CliList.add(thr);
        current++;
        thr.start();
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
コード例 #7
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);
  }
コード例 #8
0
 private void setupProxy(
     ConnectivitySettings cs, int connectionType, InetSocketAddress inetSocketAddress) {
   cs.setConnectionType(connectionType);
   InetAddress address = inetSocketAddress.getAddress();
   cs.setProxyHost((address != null) ? address.getHostAddress() : inetSocketAddress.getHostName());
   cs.setProxyPort(inetSocketAddress.getPort());
 }
コード例 #9
0
 // Check for an IP, since this seems to be safer to return then a plain name
 private String getIpIfPossible(String pHost) {
   try {
     InetAddress address = InetAddress.getByName(pHost);
     return address.getHostAddress();
   } catch (UnknownHostException e) {
     return pHost;
   }
 }
コード例 #10
0
ファイル: Downloader.java プロジェクト: dbacarel/Bitcreek
  private int contatta_Peer(FileAccess file_acc, InetAddress partner, int porta) {

    /* socket per la comunicazione TCP */
    Socket socket = null;

    PersonalServer nuovo;

    if (file_acc == null || partner == null || porta == 0) {
      System.out.println(
          "## contatta_peer ha ricevuto almeno un parametro null o porta passata 0 ! ");
      return 1;
    }

    System.out.println("@ provo a contattare il Peer " + partner.getHostAddress());

    // creo il socket
    try {
      socket = new Socket(partner, porta); // TODO 4000 è default, diventerà paramentro
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      System.out.println(
          "# eccezione nella creazione socket verso il peer:" + partner.getHostAddress());
      e1.printStackTrace();
      return 1;
    }

    System.out.println("@ socket creato ");
    System.out.println("@ streams ok, chiedo riguardo al file" + file_acc.getNome());

    if (socket != null) {
      nuovo = new PersonalServer(file_acc, socket, 1);
      if (nuovo != null) Peer.threads.aggiungi_down(nuovo);
      else {
        System.out.println(
            "# Problemi con la creazione dell'oggetto del Personal Server per "
                + file_acc.getNome());
        return 1;
      }
    } else {
      System.out.println("# Problemi con la creazione del socket con " + partner.getHostAddress());
      return 1;
    }

    return 0;
  }
コード例 #11
0
  // [JACKSON-484]
  public void testInetAddress() throws IOException {
    InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class);
    assertEquals("127.0.0.1", address.getHostAddress());

    // should we try resolving host names? That requires connectivity...
    final String HOST = "google.com";
    address = MAPPER.readValue(quote(HOST), InetAddress.class);
    assertEquals(HOST, address.getHostName());
  }
コード例 #12
0
ファイル: Chord.java プロジェクト: DevoutChaos/NetAssign3
 /**
  * @throws RemoteException
  * @throws UnknownHostException
  */
 public void stabilize() throws RemoteException, UnknownHostException {
   ChordMessageInterface succ = rmiChord(successor.getIp(), successor.getPort());
   Finger x = succ.getPredecessor();
   if (ino(x.getId(), i, successor.getId())) {
     successor = x;
   }
   InetAddress ip = InetAddress.getLocalHost();
   succ = rmiChord(successor.getIp(), successor.getPort());
   succ.notify(new Finger(ip.getHostAddress(), port, i));
 }
コード例 #13
0
ファイル: Utility.java プロジェクト: phan-pivotal/OSS
 /** Return the hostname of the local machine. */
 public static String getLocalAddress() {
   String address = null;
   try {
     InetAddress ia = InetAddress.getLocalHost();
     address = ia.getHostAddress();
   } catch (UnknownHostException e) {
     return "127.0.0.1";
   }
   return address;
 }
コード例 #14
0
ファイル: Downloader.java プロジェクト: dbacarel/Bitcreek
  private Descrittore contatta_server(String nome) {

    // variabili per l'RMI
    RMIServerInt serv = null; // server
    Descrittore descr_rit = null; // descrittore ritornato

    if (nome == null) {
      System.out.println("## contatta_server di Download ha ricevuto parametro null ! ");
      return null;
    }

    System.out.println("@ provo a contattare il server RMI ");
    // ################  RMI ################
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }

    Object o = null;
    try {
      // o = Naming.lookup("rmi://192.168.0.10:1099/srmi");
      Registry registry = LocateRegistry.getRegistry(server.getHostAddress());
      o = registry.lookup("srmi");

    } catch (RemoteException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    } catch (NotBoundException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    }

    if (o == null) {
      System.out.println(
          "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null");
      return null;
    }

    serv = (RMIServerInt) o;

    try {
      descr_rit = serv.lookup(nome, InetAddress.getLocalHost());
    } catch (RemoteException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;

    } catch (UnknownHostException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;
    }

    return descr_rit;
  }
コード例 #15
0
ファイル: Downloader.java プロジェクト: dbacarel/Bitcreek
  private int vita_sociale(FileAccess file_acc, ArrayList<InetAddress> l_peers) {
    int contattato_ok = 0;
    int problemi = 0;
    System.out.println("@ vista sociale attivata con lista  !" + l_peers.toString());

    for (InetAddress i : l_peers)
      if (!i.getHostAddress().equals("192.168.0.10")) {
        System.out.println("@ confronto gli ip di: " + i.getHostAddress() + " con 192.168.0.10");
        contattato_ok = contatta_Peer(file_acc, i, 4000);
        if (contattato_ok != 0) {
          System.out.println(
              "# il tentativo di creazione di connessione con il peer  "
                  + i.getHostAddress()
                  + " ha fallito");
          problemi = 1;
        }
      } else
        System.out.println("Evito di contattare il mio stesso indirizzo"); // TODO togliere questo

    return problemi;
  }
コード例 #16
0
 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;
 }
コード例 #17
0
 @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) {
   }
 }
コード例 #18
0
ファイル: AppFrame.java プロジェクト: CestLaVi3/Android-Mouse
  public AppFrame() {
    super();
    GlobalData.oFrame = this;
    this.setSize(this.width, this.height);
    this.toolkit = Toolkit.getDefaultToolkit();

    Dimension w = toolkit.getScreenSize();
    int fx = (int) w.getWidth();
    int fy = (int) w.getHeight();

    int wx = (fx - this.width) / 2;
    int wy = (fy - this.getHeight()) / 2;

    setLocation(wx, wy);

    this.tracker = new MediaTracker(this);
    String sHost = "";
    try {

      localAddr = InetAddress.getLocalHost();
      if (localAddr.isLoopbackAddress()) {
        localAddr = LinuxInetAddress.getLocalHost();
      }
      sHost = localAddr.getHostAddress();
    } catch (UnknownHostException ex) {
      sHost = "你的IP地址错误";
    }
    //
    this.textLines[0] = "服务器正在运行.";
    this.textLines[1] = "";
    this.textLines[2] = "你的IP地址: " + sHost;
    this.textLines[3] = "";
    this.textLines[4] = "请打开你的手机客户端";
    this.textLines[5] = "";
    this.textLines[6] = "输入屏幕上显示的IP地址.";
    //
    try {
      URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation();
      String sBase = fileURL.toString();
      if ("jar".equals(sBase.substring(sBase.length() - 3, sBase.length()))) {
        jar = new JarFile(new File(fileURL.toURI()));

      } else {
        basePath = System.getProperty("user.dir") + "\\res\\";
      }
    } catch (Exception ex) {
      this.textLines[1] = "exception: " + ex.toString();
    }
  }
コード例 #19
0
ファイル: CIManagerImpl.java プロジェクト: manoj-s/framework
  private void setMailCredential(CIJob job) {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    }
    try {
      String jenkinsTemplateDir = Utility.getJenkinsTemplateDir();
      String mailFilePath = jenkinsTemplateDir + MAIL + HYPHEN + CREDENTIAL_XML;
      if (debugEnabled) {
        S_LOGGER.debug("configFilePath ... " + mailFilePath);
      }
      File mailFile = new File(mailFilePath);

      SvnProcessor processor = new SvnProcessor(mailFile);

      //			DataInputStream in = new DataInputStream(new FileInputStream(mailFile));
      //			while (in.available() != 0) {
      //				System.out.println(in.readLine());
      //			}
      //			in.close();

      // Mail have to go with jenkins running email address
      InetAddress ownIP = InetAddress.getLocalHost();
      processor.changeNodeValue(
          CI_HUDSONURL,
          HTTP_PROTOCOL
              + PROTOCOL_POSTFIX
              + ownIP.getHostAddress()
              + COLON
              + job.getJenkinsPort()
              + FORWARD_SLASH
              + CI
              + FORWARD_SLASH);
      processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
      processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
      processor.changeNodeValue("adminAddress", job.getSenderEmailId());

      // jenkins home location
      String jenkinsJobHome = System.getenv(JENKINS_HOME);
      StringBuilder builder = new StringBuilder(jenkinsJobHome);
      builder.append(File.separator);

      processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
      S_LOGGER.error(
          "Entered into the catch block of CIManagerImpl.setMailCredential "
              + e.getLocalizedMessage());
    }
  }
コード例 #20
0
    /*
     * Returns the string representation of the address that this
     * listen key represents.
     */
    public String address() {
      InetAddress address = ss.getInetAddress();

      /*
       * If bound to the wildcard address then use current local
       * hostname. In the event that we don't know our own hostname
       * then assume that host supports IPv4 and return something to
       * represent the loopback address.
       */
      if (address.isAnyLocalAddress()) {
        try {
          address = InetAddress.getLocalHost();
        } catch (UnknownHostException uhe) {
          byte[] loopback = {0x7f, 0x00, 0x00, 0x01};
          try {
            address = InetAddress.getByAddress("127.0.0.1", loopback);
          } catch (UnknownHostException x) {
            throw new InternalError("unable to get local hostname");
          }
        }
      }

      /*
       * Now decide if we return a hostname or IP address. Where possible
       * return a hostname but in the case that we are bound to an
       * address that isn't registered in the name service then we
       * return an address.
       */
      String result;
      String hostname = address.getHostName();
      String hostaddr = address.getHostAddress();
      if (hostname.equals(hostaddr)) {
        if (address instanceof Inet6Address) {
          result = "[" + hostaddr + "]";
        } else {
          result = hostaddr;
        }
      } else {
        result = hostname;
      }

      /*
       * Finally return "hostname:port", "ipv4-address:port" or
       * "[ipv6-address]:port".
       */
      return result + ":" + ss.getLocalPort();
    }
コード例 #21
0
  private static void aguardarConexao() throws Exception {
    ServidorApp.srvApp = new ServerSocket(_porta);
    System.out.println("\nA Porta " + _porta + " foi ABERTA! \nAguardando nova conexao...");
    InetAddress inet = InetAddress.getByName("localhost");

    while (true) {
      ServidorApp.sk = srvApp.accept();
      System.out.println("Informacao coletada do cliente...");
      System.out.println(inet.getHostAddress());
      System.out.println(inet.getHostName());

      BufferedReader recebercliente =
          new BufferedReader(new InputStreamReader(sk.getInputStream()));

      ServidorApp.msg_cliente = recebercliente.readLine();
      System.out.println("Mensagem Recebida do Cliente: " + msg_cliente);
    }
  }
コード例 #22
0
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
コード例 #23
0
 /** Converts rdata to a String */
 public String rrToString() {
   InetAddress addr;
   try {
     addr = InetAddress.getByAddress(null, address);
   } catch (UnknownHostException e) {
     return null;
   }
   if (addr.getAddress().length == 4) {
     // Deal with Java's broken handling of mapped IPv4 addresses.
     StringBuffer sb = new StringBuffer("0:0:0:0:0:ffff:");
     int high = ((address[12] & 0xFF) << 8) + (address[13] & 0xFF);
     int low = ((address[14] & 0xFF) << 8) + (address[15] & 0xFF);
     sb.append(Integer.toHexString(high));
     sb.append(':');
     sb.append(Integer.toHexString(low));
     return sb.toString();
   }
   return addr.getHostAddress();
 }
コード例 #24
0
ファイル: UdpServer.java プロジェクト: faustvault/JDE-Samples
  public void run() {

    System.out.println("               -----------------UDP Demo Server-----------------" + "\n\n");

    while (true) {
      try {
        // Create a new socket connection bound to the defined port
        DatagramSocket sock = new DatagramSocket(BROADCAST_PORT);

        System.out.println("Waiting for data on local port: " + sock.getLocalPort());

        // Create a packet to contain incoming data
        byte[] buf = new byte[256];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        // Wait for incoming data (receive() is a blocking method)
        sock.receive(packet);

        // Retrieve data from packet and display
        String data = new String(packet.getData());
        int endIndex = data.indexOf(0);
        data = data.substring(0, endIndex);
        int remotePort = packet.getPort();
        System.out.println("Received data from remote port " + remotePort + ":\n" + data);

        // Determine origin of packet and display information
        InetAddress remoteAddress = packet.getAddress();
        System.out.println("Sent from address: " + remoteAddress.getHostAddress());

        // Send back an acknowledgment
        String ack = "RECEIVED " + new Date().toString();
        sock.send(new DatagramPacket(ack.getBytes(), ack.length(), remoteAddress, remotePort));

        sock.close();
      } catch (IOException ioe) {
        System.out.println("Error: IOException - " + ioe.toString());
      }
    }
  }
コード例 #25
0
    @Override
    public void run() {

      try {
        // Create a server socket
        ServerSocket serverSocket = new ServerSocket(8000);
        textArea.append("TCP connection listener started at " + new Date() + '\n');

        while (true) {

          // Listen for a new connection request
          Socket socket = serverSocket.accept();

          // Display the client number
          textArea.append(
              "Starting thread for TCP client " + clientNo + " at " + new Date() + '\n');

          // Find the client's host name, and IP address
          InetAddress inetAddress = socket.getInetAddress();
          textArea.append(
              "Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
          textArea.append(
              "Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");

          // Create a new thread for the TCP connection
          HandleTCPClient task = new HandleTCPClient(socket);

          // Start the new thread
          new Thread(task).start();

          // Increment clientNo
          clientNo++;
        }

      } catch (IOException ex) {
        System.err.println(ex);
      }
    }
コード例 #26
0
ファイル: server.java プロジェクト: michi-goetz/java-chat
 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();
   }
 }
コード例 #27
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 "";
 }
コード例 #28
0
ファイル: Chord.java プロジェクト: DevoutChaos/NetAssign3
  /**
   * @param _port
   * @param id
   * @throws RemoteException
   * @throws UnknownHostException
   */
  public Chord(int _port, int id) throws RemoteException, UnknownHostException {
    finger = new Finger[(1 << M)]; // 1 << M = 2^(M)
    // TODO: set the fingers in the array to null
    i = id;
    port = _port;
    // TODO: determine the current IP of the machine

    predecessor = null;
    InetAddress ip = InetAddress.getLocalHost();
    successor = new Finger(ip.getHostAddress(), i, i);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          @Override
          public void run() {
            try {
              stabilize();
            } catch (RemoteException | UnknownHostException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            fixFingers();
            checkPredecessor();
          }
        },
        500,
        500);
    try {
      // create the registry and bind the name and object.
      System.out.println("Starting RMI at port=" + port);
      registry = LocateRegistry.createRegistry(port);
      registry.rebind("Chord", this);
    } catch (RemoteException e) {
      throw e;
    }
  }
コード例 #29
0
ファイル: Util.java プロジェクト: gubo/slipwire
  /** @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;
  }
コード例 #30
0
ファイル: EchoAWT.java プロジェクト: operationcwal/app
  public EchoAWT() throws UnknownHostException {

    super("채팅 프로그램");

    // 각종 정의
    h = new JPanel(new GridLayout(2, 3));
    m = new JPanel(new BorderLayout());
    f = new JPanel(new BorderLayout());
    s = new JPanel(new BorderLayout());
    login = new JPanel(new BorderLayout());

    // name = new JLabel(" 사용자 이름 ");
    name = new JLabel(" 메세지 입력 ");

    jta = new JTextArea();
    // clientList = new JTextArea(0, 10);
    clientList = new JList();

    jsp = new JScrollPane(jta);
    list = new JScrollPane(clientList);

    jtf = new JTextField("입력하세요.");
    hi = new JTextField("HOST IP 입력");
    pi = new JTextField("PORT 입력");
    localport = new JTextField("원하는 PORT 입력");
    lid = new JTextField("ID를 입력하세요.");
    lpw = new JTextField("PW를 입력하세요.");

    serveropen = new JButton("서버 오픈");
    textin = new JButton("입력");
    clientin = new JButton("서버 접속");
    conf = new JButton("로그인");
    join = new JButton("회원가입");

    addr = InetAddress.getLocalHost();

    // 사용자 해상도 및 창 크기 설정 및 가져오기.
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension screenSize = tk.getScreenSize();

    setSize(500, 500);
    Dimension d = getSize();

    // 각종 버튼 및 텍스트 필드 리스너
    jtf.addActionListener(this);
    hi.addActionListener(this);
    pi.addActionListener(this);
    localport.addActionListener(this);
    lid.addActionListener(this);
    lpw.addActionListener(this);
    conf.addActionListener(this);
    join.addActionListener(this);

    serveropen.addActionListener(this);
    clientin.addActionListener(this);
    textin.addActionListener(this);

    jtf.addFocusListener(this);
    hi.addFocusListener(this);
    pi.addFocusListener(this);
    localport.addFocusListener(this);
    lid.addFocusListener(this);
    lpw.addFocusListener(this);

    // 서버 접속
    h.add(hi);
    h.add(pi);
    h.add(clientin);

    // 서버 생성
    h.add(new JLabel("IP : " + addr.getHostAddress(), (int) CENTER_ALIGNMENT));
    h.add(localport);
    h.add(serveropen);

    // 채팅글창 글 작성 막기
    jta.setEditable(false);

    // 접속자 리스트 width 제한
    clientList.setFixedCellWidth(d.width / 3);

    // 입력 창
    f.add(name, "West");
    f.add(jtf, "Center");
    f.add(textin, "East");

    // 접속자 확인창
    s.add(new JLabel("접속자", (int) CENTER_ALIGNMENT), "North");
    s.add(list, "Center");
    // clientList.setEditable(false);

    // 메인 창
    m.add(jsp, "Center");
    m.add(s, "East");

    // 프레임 설정
    add(h, "North");
    add(m, "Center");
    add(f, "South");

    // 로그인 다이얼로그
    jd = new JDialog();
    jd.setTitle("채팅 로그인");
    jd.add(login);
    jd.setSize(200, 200);
    Dimension dd = jd.getSize();
    jd.setLocation(screenSize.width / 2 - (dd.width / 2), screenSize.height / 2 - (dd.height / 2));
    jd.setVisible(true);

    // 로그인창
    JPanel lm = new JPanel(new GridLayout(4, 1));
    lm.add(lid);
    lm.add(new Label());
    lm.add(lpw);
    lm.add(new Label());

    JPanel bt = new JPanel();
    bt.add(conf);
    bt.add(join);

    login.add(new Label(), "North");
    login.add(new Label(), "West");
    login.add(new Label(), "East");
    login.add(lm, "Center");
    login.add(bt, "South");

    // 창의 위치, 보임, EXIT 단추 활성화.
    setLocation(screenSize.width / 2 - (d.width / 2), screenSize.height / 2 - (d.height / 2));

    setVisible(false);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }