예제 #1
1
  @Override
  public void run() {
    // TODO Auto-generated method stub
    if (localAddress == null) {
      Log.w(LOGTAG, "no network address avalibe to listen");
      return;
    }
    ServerSocket Server;
    try {

      Server = new ServerSocket(port, 10, localAddress);

      System.out.println(
          "TCPServer Waiting for client on " + localAddress.getHostAddress() + ": " + port);

      while (true) {
        Socket connected = Server.accept();
        (new HttpServer(connected)).start();
      }
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Constructor. Creates a datagram send socket and connects it to the Ganglia hypertable extension
   * listen port. Initializes mPrefix to "ht." + <code>component</code> + ".".
   *
   * @param component Hypertable component ("fsbroker", "hyperspace, "master", "rangeserver", or
   *     "thriftbroker")
   * @param props Configuration properties
   */
  public MetricsCollectorGanglia(String component, Properties props) {
    mPrefix = "ht." + component + ".";

    String str = props.getProperty("Hypertable.Metrics.Ganglia.Port", "15860");
    mPort = Integer.parseInt(str);

    str = props.getProperty("Hypertable.Metrics.Ganglia.Disabled");
    if (str != null && str.equalsIgnoreCase("true")) mDisabled = true;

    try {
      mAddr = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException : 'localhost'");
      e.printStackTrace();
      System.exit(-1);
    }

    try {
      mSocket = new DatagramSocket();
    } catch (SocketException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    mSocket.connect(mAddr, mPort);
    mConnected = true;
  }
  @Override
  protected Inet6Address ipAddressRandomizer(InetAddress realAddress) {
    byte[] addr = {
      realAddress.getAddress()[0],
      realAddress.getAddress()[1],
      realAddress.getAddress()[2],
      realAddress.getAddress()[3],
      realAddress.getAddress()[4],
      realAddress.getAddress()[5],
      realAddress.getAddress()[6],
      realAddress.getAddress()[7],
      realAddress.getAddress()[8],
      realAddress.getAddress()[9],
      realAddress.getAddress()[10],
      realAddress.getAddress()[11],
      (byte) 0,
      (byte) 0,
      (byte) 0,
      (byte) 0
    };

    Inet6Address fakeV4 = null;
    try {
      fakeV4 = (Inet6Address) Inet6Address.getByAddress(addr);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }

    return fakeV4;
  }
  /**
   * Tries to start a server on the specified port.
   *
   * @param host - host name (IP) to use
   * @param port - port to use for opened socket
   */
  private void init(String host, int port) {
    if (host != null) {
      this.host = host;
    } else {
      try {
        this.host = InetAddress.getLocalHost().getHostAddress();
      } catch (UnknownHostException xcp) {
        xcp.printStackTrace();
        this.host = null;
      }
    }

    try {
      serverSocket = new ServerSocket(port);
    } catch (IOException xcp) {
      handleFailureToCreateServerSocket(port, xcp);
      return;
    }

    // Get port being used for server socket
    this.port = serverSocket.getLocalPort();

    // Create a server thread and start it listening
    Runnable serverConnectionDaemon = new ServerConnectionDaemon();
    ThreadTools.startAsDaemon(serverConnectionDaemon, "Data Object Server Conn Daemon");

    printIfDebug(
        ".init: comm server started listening on:\n"
            + "\thost = "
            + this.host
            + "\n\tport = "
            + this.port);
  }
예제 #5
0
  private boolean connectSPPMon() {
    if (state == ConnectionEvent.CONNECTION_PENDING) {
      ExpCoordinator.print(
          new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0);
      while (state == ConnectionEvent.CONNECTION_PENDING) {
        try {
          Thread.sleep(500);
        } catch (java.lang.InterruptedException e) {
        }
      }
      return (isConnected());
    }

    state = ConnectionEvent.CONNECTION_PENDING;
    if (nonProxy != null) {
      try {
        nonProxy.connect();
      } catch (UnknownHostException e) {
        boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage());
        return rtn;
      } catch (SocketTimeoutException e) {
        boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage());
        return rtn;
      } catch (IOException e) {
        boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage());
        return rtn;
      }
    }
    return (isConnected());
  }
예제 #6
0
    @Override
    public void connectController(String host, int port) {
      if (host == null) {
        host = defaultControllerHost;
      }

      if (port < 0) {
        port = defaultControllerPort;
      }

      try {
        ModelControllerClient newClient = ModelControllerClient.Factory.create(host, port);
        if (this.client != null) {
          disconnectController();
        }

        List<String> nodeTypes = Util.getNodeTypes(newClient, new DefaultOperationRequestAddress());
        if (!nodeTypes.isEmpty()) {
          domainMode = nodeTypes.contains("server-group");
          printLine(
              "Connected to "
                  + (domainMode ? "domain controller at " : "standalone controller at ")
                  + host
                  + ":"
                  + port);
          client = newClient;
          this.controllerHost = host;
          this.controllerPort = port;
        } else {
          printLine("The controller is not available at " + host + ":" + port);
        }
      } catch (UnknownHostException e) {
        printLine("Failed to resolve host '" + host + "': " + e.getLocalizedMessage());
      }
    }
예제 #7
0
  private static boolean isLive(String aServer) {
    try {
      URL url = new URL(aServer + "health");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url);
      }

      if (uc.getResponseCode() == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element response = (Element) xml.getRootElement();
        Element health = response.getFirstChildElement("health");
        String status = health.getValue();

        if (status.equals("dying") || status.equals("sick")) {
          if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status);
          }

          return true;
        } else if (status.equals("ok")) {
          return true;
        } else {
          LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status);
        }
      }
    } catch (UnknownHostException details) {
      LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage());
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }

    return false;
  }
예제 #8
0
 /**
  * 下载文件
  *
  * @param params 请求参数
  * @param filepath 保存路径
  */
 public static File downloadFile(RequestParams params, String filepath) throws TaskException {
   // 设置断点续传
   params.setAutoResume(true);
   params.setSaveFilePath(filepath);
   try {
     return x.http().getSync(params, File.class);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
예제 #9
0
 public static <T> T doPostSync(RequestParams params, Class<T> responseCls) throws TaskException {
   try {
     return x.http().postSync(params, responseCls);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
예제 #10
0
 /**
  * 获取本机ip
  *
  * @return
  */
 public static String GetIpAdd() {
   try {
     return InetAddress.getLocalHost().getHostAddress();
   } catch (UnknownHostException e) { // TODO 自动生成 catch 块
     return e.getMessage(); // e.printStackTrace();
   }
 }
예제 #11
0
  public Server() {
    try {
      ServerSocket ss = new ServerSocket(SERVER_PORT);

      Socket s = ss.accept();

      InputStream is = s.getInputStream();
      OutputStream out = s.getOutputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String sss = br.readLine();
      System.out.println(sss);

      PrintWriter pw = new PrintWriter(out);
      pw.print("hello,我是服务器。");

      pw.close();
      br.close();
      isr.close();
      out.close();
      is.close();
      s.close();
      ss.close();
    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (IOException oe) {
      oe.printStackTrace();
    }
  }
  /**
   * Client application will be started with the main() of the {@link ClientServicesStarter}
   *
   * @param args the parameter which is passed to the main()
   */
  public static void startClient() {

    try {
      props.put("client.ip", InetAddress.getLocalHost().getHostAddress());

    } catch (IOException e) {
      e.printStackTrace();
    }

    ClientServicesStarter client = new ClientServicesStarter();
    RemoteNodeRegistration nodeRegister = (RemoteNodeRegistration) client.startProxy();

    try {
      if (nodeRegister != null) {
        String SERVER_IP = nodeRegister.registerNode(InetAddress.getLocalHost().getHostAddress());
        ClientServicesStarter.serverName(SERVER_IP);
        client.loadNode();
      } else {
        log.debug("Server at " + props.getProperty("server.ip") + " not found");
        System.exit(1);
      }

    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }
예제 #13
0
  /**
   * Creates a {@link Connection} with {@link Connection.Modality#Synchronous} semantics suitable
   * for use by synchronous (blocking) JRedis clients.
   *
   * <p>[TODO: this method should be using connection spec!]
   *
   * @param host
   * @param port
   * @param redisVersion
   * @return
   */
  protected Connection createSynchConnection(String host, int port, RedisVersion redisVersion) {
    InetAddress address = null;
    Connection synchConnection = null;
    try {

      address = InetAddress.getByName(host);
      synchConnection = new SynchConnection(address, port, redisVersion);
      Assert.notNull(synchConnection, "connection delegate", ClientRuntimeException.class);
    } catch (NotSupportedException e) {
      Log.log("Can not support redis protocol '%s'", redisVersion);
      throw e;
    } catch (ProviderException e) {
      Log.bug("Couldn't create the handler delegate.  => " + e.getLocalizedMessage());
      throw e;
    } catch (ClientRuntimeException e) {
      String msg = e.getMessage() + "\nMake sure your server is running.";
      Log.error("Error creating connection -> " + e.getLocalizedMessage());
      setConnection(new FaultedConnection(msg));
    } catch (UnknownHostException e) {
      String msg = "Couldn't obtain InetAddress for " + host;
      Log.problem(msg + "  => " + e.getLocalizedMessage());
      throw new ClientRuntimeException(msg, e);
    }
    return synchConnection;
  }
예제 #14
0
  /**
   * Funcion que permite publicar la url del servicio Web
   *
   * @param arg
   */
  public static void main(String arg[]) {
    String ip = "";
    String puerto = "";

    try {
      ResourceBundle rb = ResourceBundle.getBundle("co.com.codesoftware.properties.baseProperties");
      String valida = rb.getString("IP_DINAMICA");

      if ("SI".equalsIgnoreCase(valida)) {
        ip = rb.getString("IP_FIJA");
      } else {
        ip = InetAddress.getLocalHost().getHostAddress();
      }
      puerto = rb.getString("PUERTO");
    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("Este es la ip: " + ip);
    Endpoint.publish("http://" + ip + ":" + puerto + "/WS/server", new SAFWS());
    System.out.println(
        "Servicos desplegados en la siguiente direccion: \n\n\n"
            + "http://"
            + ip
            + ":"
            + puerto
            + "/WS/server/SAFWS?wsdl");
  }
  /** Initializes the query system by binding it to a port */
  private boolean initQuerySystem() {
    try {
      querySocket = new DatagramSocket(queryPort, InetAddress.getByName(serverHostname));
      registerSocket(querySocket);
      querySocket.setSoTimeout(500);
      return true;
    } catch (SocketException var2) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Socket): "
              + var2.getMessage());
    } catch (UnknownHostException var3) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (Unknown Host): "
              + var3.getMessage());
    } catch (Exception var4) {
      logWarning(
          "Unable to initialise query system on "
              + serverHostname
              + ":"
              + queryPort
              + " (E): "
              + var4.getMessage());
    }

    return false;
  }
  public Process(String name, int pid, int n) {

    this.name = name;
    this.port = Utils.REGISTRAR_PORT + pid;

    this.host = "UNKNOWN";
    try {
      this.host = (InetAddress.getLocalHost()).getHostName();

    } catch (UnknownHostException e) {
      String msg = String.format("Error: getHostName() failed at %s.", this.getInfo());
      System.err.println(msg);
      System.err.println(e.getMessage());
      System.exit(1);
    }

    this.pid = pid;
    this.n = n;

    random = new Random();

    /* Accepts connections from one of Registrar's worker threads */
    new Thread(new Listener(this)).start();
    /* Connect to registrar */
    socket = connect();
    init();
    Utils.out(pid, "Connected.");
  }
  public RConQueryThread(IServer par1IServer) {
    queryPort = ModuleSnooper.port;
    serverHostname = ModuleSnooper.hostname;
    serverPort = par1IServer.getPort();
    queryHostname = "0.0.0.0";
    server = par1IServer;

    if (0 != serverHostname.length() && !queryHostname.equals(serverHostname)) {
      queryHostname = serverHostname;
    } else {
      serverHostname = "0.0.0.0";

      try {
        InetAddress var2 = InetAddress.getLocalHost();
        queryHostname = var2.getHostAddress();
      } catch (UnknownHostException var3) {
        logWarning(
            "Unable to determine local host IP, please set server-ip/hostname in the snooper config : "
                + var3.getMessage());
      }
    }

    if (0 == queryPort) {
      queryPort = serverPort;
      logInfo("Setting default query port to " + queryPort);
    }

    field_72644_p = new HashMap();

    queryClients = new HashMap();
    time = (new Date()).getTime();
  }
예제 #18
0
 /**
  * gets the time from the creeperhost servers
  *
  * @return - the time in the DDMMYY format
  */
 public static String getTime() {
   String content = null;
   Scanner scanner = null;
   int retries = 1;
   try {
     HttpURLConnection connection =
         (HttpURLConnection) new URL("http://repo.creeperhost.net/getdate").openConnection();
     while (connection.getResponseCode() != 200 && retries <= 3) {
       connection.disconnect();
       connection =
           (HttpURLConnection)
               new URL("http://repo" + retries + ".creeperhost.net/getdate").openConnection();
       retries++;
     }
     scanner = new Scanner(connection.getInputStream());
     scanner.useDelimiter("\\Z");
     content = scanner.next();
     connection.disconnect();
   } catch (java.net.UnknownHostException uhe) {
     Logger.logError(uhe.getMessage(), uhe);
   } catch (Exception ex) {
     Logger.logError(ex.getMessage(), ex);
   } finally {
     if (scanner != null) {
       scanner.close();
     }
   }
   return content;
 }
예제 #19
0
 static {
   try {
     hostname = InetAddress.getLocalHost().getHostName();
   } catch (UnknownHostException e) {
     e.printStackTrace();
   }
 }
예제 #20
0
 /**
  * Checks the file for corruption.
  *
  * @param file - File to check
  * @return - boolean representing if it is valid
  * @throws IOException
  */
 public static boolean isValid(File file) throws IOException {
   String content = null;
   Scanner scanner = null;
   int retries = 1;
   try {
     HttpURLConnection connection =
         (HttpURLConnection)
             new URL("http://repo.creeperhost.net/md5/FTB2/" + file.getName()).openConnection();
     while (connection.getResponseCode() != 200 && retries <= 3) {
       connection.disconnect();
       connection =
           (HttpURLConnection)
               new URL("http://repo" + retries + ".creeperhost.net/md5/FTB2/" + file.getName())
                   .openConnection();
       retries++;
     }
     scanner = new Scanner(connection.getInputStream());
     scanner.useDelimiter("\\Z");
     content = scanner.next();
     connection.disconnect();
   } catch (java.net.UnknownHostException uhe) {
     Logger.logError(uhe.getMessage(), uhe);
   } catch (Exception ex) {
     Logger.logError(ex.getMessage(), ex);
   } finally {
     if (scanner != null) {
       scanner.close();
     }
   }
   String result = fileMD5(file);
   Logger.logInfo(result);
   return content.equalsIgnoreCase(result);
 }
  public void event(WatchEvent.Kind kind, Path path) {
    // System.out.println("Log event");

    File file = new File(path.toString());
    String ip = "0.0.0.0", owner = "unknown";
    try {
      ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    try {
      FileOwnerAttributeView ownerAttributeView =
          Files.getFileAttributeView(path, FileOwnerAttributeView.class);
      owner = ownerAttributeView.getOwner().getName();
    } catch (IOException e) {
      e.printStackTrace();
    }

    String entry =
        String.format(
            "[%s] \"%s\" copied on \"%s\" by \"%s\"\n",
            new SimpleDateFormat("dd/MMM/YYYY HH:mm:ss").format(new Date()),
            path.toString(),
            ip,
            owner);

    try {
      Files.write(Paths.get(logFile), entry.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #22
0
  void sendMessage(String msg) {
    try {
      ObjectOutputStream outputToAnotherObject = null;
      ObjectInputStream inputFromAnotherObject = null;
      Thread.sleep(500);

      // Send 5 messages to the Server

      // write to socket using ObjectOutputStream
      outputToAnotherObject =
          new ObjectOutputStream(getRoverSocket().getNewSocket().getOutputStream());

      System.out.println("=================================================");
      System.out.println("RAD Client: Sending request to Socket Server");
      System.out.println("=================================================");

      outputToAnotherObject.writeObject(msg);

      // read the server response message
      inputFromAnotherObject = new ObjectInputStream(getRoverSocket().getSocket().getInputStream());
      String message = (String) inputFromAnotherObject.readObject();
      System.out.println("RAD Client received: " + message.toUpperCase());

      // close resources
      inputFromAnotherObject.close();
      outputToAnotherObject.close();
      Thread.sleep(100);

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception error) {
      System.out.println("Client: Error:" + error.getMessage());
    }
  }
예제 #23
0
  public static void main(String[] args) {
    try {
      ServerSocket socket = new ServerSocket(8606, 50, InetAddress.getByName("localhost"));
      Socket client = socket.accept();

      OutputStream out = client.getOutputStream();
      InputStream in = client.getInputStream();

      DataOutputStream dout = new DataOutputStream(out);
      DataInputStream din = new DataInputStream(in);

      String line = null;

      while (true) {
        line = din.readUTF();
        System.out.println(line);
        dout.writeUTF(line);
      }

    } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
예제 #24
0
  /**
   * This method created a socket and a packet. It is performed only once in
   *
   * <p>the constructor of JoyActivity.
   *
   * <p>Indeed, two objects are required for UDP communication, a socket and a
   *
   * <p>packet as respective class DatagramSocket and DatagramPacket (classes
   *
   * <p>available in the Android libraries).
   *
   * @param ComandeUDP start command
   * @param port The Port to use
   * @param host The Address IP target
   */
  public DatagramSocket CreationSocketPacket(String ComandeUDP, int port, String host) {
    buffer = new byte[512];

    try { // TRY CREATION SOCKET
      udp_socket = new DatagramSocket();

    } catch (SocketException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try { // INSERTION TRAME
      buffer = ComandeUDP.concat("\r").getBytes("ASCII");

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    try { // INSERTION ADRESSE
      adresse = InetAddress.getByName(host);
    } catch (UnknownHostException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    udp_packet = new DatagramPacket(buffer, buffer.length, adresse, port);
    return udp_socket;
  }
예제 #25
0
 public static void createBoltIdentifyingFiles(TopologyContext topologyContext) {
   String componentName = topologyContext.getThisComponentId();
   Long ts = System.currentTimeMillis();
   String fileName = "bolt-" + ts + "-" + componentName + ".log";
   File file =
       new File(
           in.dream_lab.stream.eventgen.utils.GlobalConstants.defaultBoltDirectory + fileName);
   try {
     FileWriter fw = new FileWriter(file);
     BufferedWriter bw = new BufferedWriter(fw);
     String rowString =
         InetAddress.getLocalHost().getHostName()
             + ","
             + Thread.currentThread().getName()
             + ","
             + componentName
             + ","
             + ts;
     bw.write(rowString);
     bw.flush();
     bw.close();
   } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  private void getTweetWithRTCountGreaterThan(int gt) {

    Mongo mongo = null;
    try {
      mongo = new Mongo(MONGO_DB_HOST, MONGO_DB_PORT);
      DB db = mongo.getDB(MONGO_DB_NAME);
      DBCollection collection = db.getCollection(MONGO_DB_COLLECTION);

      DBCursor cursor = collection.find(new BasicDBObject("rTCount", new BasicDBObject("$gt", gt)));

      DBObject dbObject;

      System.out.println("\n\n========================================");
      System.out.println("Displaying Tweet with RTCount > " + gt);

      while (cursor.hasNext()) {
        dbObject = cursor.next();
        System.out.println(
            "user "
                + dbObject.get("user")
                + "tweet "
                + dbObject.get("tweet")
                + " RTCount "
                + dbObject.get("rTCount"));
      }

      System.out.println("========================================\n\n");

    } catch (UnknownHostException e) {
      e.printStackTrace();
    } finally {
      if (mongo != null) mongo.close();
    }
  }
예제 #27
0
  // 获得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;
  }
예제 #28
0
  @Override
  public void run() {

    if (clientIP.length() > 0) {
      Integer portTo =
          Integer.parseInt(JRadiusConfigurator.getInstance().getProperty("send2ip_port"));

      if (JRadiusConfigurator.getInstance().getProperty("send_by_self").equals("enabled")) {

        Socket toServer;
        try {
          toServer = new Socket(clientIP, portTo);
          OutputStream serverOut = new BufferedOutputStream(toServer.getOutputStream());
          serverOut.write(message.getBytes());
          toServer.close();
        } catch (UnknownHostException e) {
          logger.error("Send2ip Unknown host error: " + e.getMessage());
        } catch (IOException e) {
          logger.error("Send2ip error: " + e.getMessage());
        }
      } else {
        try {
          String execStr = JRadiusConfigurator.getInstance().getProperty("send_program");
          execStr = String.format(execStr + " %s %s '%s'", clientIP, portTo, message);
          Process p = Runtime.getRuntime().exec(execStr);
          p.waitFor();
          logger.info("Execute send2ip program result: " + p.exitValue());
        } catch (Exception e) {
          logger.error("Error executing send2ip program: " + e.getMessage());
        }
      }
    }
  }
예제 #29
0
  /**
   * Barrier constructor
   *
   * @param address
   * @param root
   * @param size
   */
  Barrier(String address, String root, int size) {
    super(address);
    this.input = input;
    this.size = size;

    // Create barrier node
    if (zk != null) {
      try {
        Stat s = zk.exists(root, false);
        if (s == null) {
          zk.create(input, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
      } catch (KeeperException e) {
        System.out.println("Keeper exception when instantiating queue: " + e.toString());
      } catch (InterruptedException e) {
        System.out.println("Interrupted exception");
      }
    }

    // My node name
    try {
      name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
    } catch (UnknownHostException e) {
      System.out.println(e.toString());
    }
  }
예제 #30
0
  public static String getLocalAddress() {
    try {
      // 遍历网卡,查找一个非回路ip地址并返回
      Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
      InetAddress ipv6Address = null;
      while (enumeration.hasMoreElements()) {
        final NetworkInterface networkInterface = enumeration.nextElement();
        final Enumeration<InetAddress> en = networkInterface.getInetAddresses();
        while (en.hasMoreElements()) {
          final InetAddress address = en.nextElement();
          if (!address.isLoopbackAddress()) {
            if (address instanceof Inet6Address) {
              ipv6Address = address;
            } else {
              // 优先使用ipv4
              return normalizeHostAddress(address);
            }
          }
        }
      }
      // 没有ipv4,再使用ipv6
      if (ipv6Address != null) {
        return normalizeHostAddress(ipv6Address);
      }
      final InetAddress localHost = InetAddress.getLocalHost();
      return normalizeHostAddress(localHost);
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }

    return null;
  }