Exemplo n.º 1
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;
  }
Exemplo n.º 2
0
  /**
   * Creates a new, empty SessionDescription. The session is set as follows:
   *
   * <p>v=0
   *
   * <p>o=this.createOrigin ("user", InetAddress.getLocalHost().toString());
   *
   * <p>s=-
   *
   * <p>t=0 0
   *
   * @throws SdpException SdpException, - if there is a problem constructing the SessionDescription.
   * @return a new, empty SessionDescription.
   */
  public SessionDescription createSessionDescription() throws SdpException {
    SessionDescriptionImpl sessionDescriptionImpl = new SessionDescriptionImpl();

    ProtoVersionField ProtoVersionField = new ProtoVersionField();
    ProtoVersionField.setVersion(0);
    sessionDescriptionImpl.setVersion(ProtoVersionField);

    OriginField originImpl = null;
    try {
      originImpl =
          (OriginField) this.createOrigin("user", InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    sessionDescriptionImpl.setOrigin(originImpl);

    SessionNameField sessionNameImpl = new SessionNameField();
    sessionNameImpl.setValue("-");
    sessionDescriptionImpl.setSessionName(sessionNameImpl);

    TimeDescriptionImpl timeDescriptionImpl = new TimeDescriptionImpl();
    TimeField timeImpl = new TimeField();
    timeImpl.setZero();
    timeDescriptionImpl.setTime(timeImpl);
    Vector times = new Vector();
    times.addElement(timeDescriptionImpl);
    sessionDescriptionImpl.setTimeDescriptions(times);

    sessionDescriptionsList.addElement(sessionDescriptionImpl);
    return sessionDescriptionImpl;
  }
Exemplo n.º 3
0
  /**
   * Workaround for the problem encountered in certains JDKs that a thread listening on a socket
   * cannot be interrupted. Therefore we just send a dummy datagram packet so that the thread 'wakes
   * up' and realizes it has to terminate. Should be removed when all JDKs support
   * Thread.interrupt() on reads. Uses sock t send dummy packet, so this socket has to be still
   * alive.
   *
   * @param dest The destination host. Will be local host if null
   * @param port The destination port
   */
  void sendDummyPacket(InetAddress dest, int port) {
    DatagramPacket packet;
    byte[] buf = {0};

    if (dest == null) {
      try {
        dest = InetAddress.getLocalHost();
      } catch (Exception e) {
      }
    }

    if (Trace.debug) {
      Trace.info("UDP.sendDummyPacket()", "sending packet to " + dest + ":" + port);
    }
    if (sock == null || dest == null) {
      Trace.warn(
          "UDP.sendDummyPacket()", "sock was null or dest was null, cannot send dummy packet");
      return;
    }
    packet = new DatagramPacket(buf, buf.length, dest, port);
    try {
      sock.send(packet);
    } catch (Throwable e) {
      Trace.error(
          "UDP.sendDummyPacket()",
          "exception sending dummy packet to " + dest + ":" + port + ": " + e);
    }
  }
Exemplo n.º 4
0
  /** 启动初始化,他确定网络中有多少个其它UDPBase和相关的信息 */
  public void initNet() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      localIP = InetAddress.getLocalHost().getHostAddress();
      int i = localIP.lastIndexOf('.');
      BROADCAST_ADDR = localIP.substring(0, i) + ".255";
      // System.out.println ("lip=="+localIP) ;
      // sendSocket = new DatagramSocket () ;
      // recvSocket = new MulticastSocket (RECV_PORT) ;
      recvSocket = new DatagramSocket(RECV_PORT);
      sendSocket = recvSocket;
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(BROADCAST_ADDR);
      // recvSocket.joinGroup (group) ;
      // recvAckSocket.joinGroup (group) ;

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
  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.");
  }
Exemplo n.º 6
0
  /**
   * Creates a new Server object.
   *
   * @param sqlDriver JDBC driver
   * @param dbURL JDBC connection url
   * @param dbLogin database login
   * @param dbPasswd database password
   */
  private Server(ServerConfig config) {
    Server.instance = this;
    this.connections = new ArrayList();
    this.services = new ArrayList();
    this.port = config.getPort();
    this.socket = null;
    this.dbLayer = null;

    try {
      dbLayer = DatabaseAbstractionLayer.createLayer(config);
      Logging.getLogger().finer("dbLayer   : " + dbLayer);

      this.store = new Store(config);
    } catch (Exception ex) {
      Logging.getLogger().severe("#Err > Unable to connect to the database : " + ex.getMessage());
      ex.printStackTrace();
      System.exit(1);
    }

    try {
      this.serverIp = InetAddress.getLocalHost().getHostAddress();
      this.socket = new ServerSocket(this.port);
    } catch (IOException e) {
      Logging.getLogger().severe("#Err > Unable to listen on the port " + port + ".");
      e.printStackTrace();
      System.exit(1);
    }

    loadInternalServices();
  }
  /** 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);
      }
    }
  }
Exemplo n.º 8
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
Exemplo n.º 9
0
 /**
  * @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));
 }
Exemplo n.º 10
0
 /**
  * Creates a SimpleResolver that will query the specified host
  *
  * @exception UnknownHostException Failure occurred while finding the host
  */
 public SimpleResolver(String hostname) throws UnknownHostException {
   if (hostname == null) {
     hostname = ResolverConfig.getCurrentConfig().server();
     if (hostname == null) hostname = defaultResolver;
   }
   InetAddress addr;
   if (hostname.equals("0")) addr = InetAddress.getLocalHost();
   else addr = InetAddress.getByName(hostname);
   address = new InetSocketAddress(addr, DEFAULT_PORT);
 }
Exemplo n.º 11
0
  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;
  }
Exemplo n.º 12
0
  static {
    DATE_FORMAT = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy z", Locale.US);

    // detect host name
    String hostName = "";
    try {
      hostName = InetAddress.getLocalHost().getHostName();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    HOST_NAME = hostName;
  }
Exemplo n.º 13
0
  /** 启动初始化,不接受任何信息包,也不发送任何信息包 */
  public void initNull() throws UDPBaseException {
    try {
      localIP = InetAddress.getLocalHost().getHostAddress();
      int i = localIP.lastIndexOf('.');
      BROADCAST_ADDR = localIP.substring(0, i) + ".255";

      bInitNull = true;
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Exemplo n.º 14
0
 protected String getHostName() {
   String res = ConfigManager.getPlatformHostname();
   if (res == null) {
     try {
       InetAddress inet = InetAddress.getLocalHost();
       return inet.getHostName();
     } catch (UnknownHostException e) {
       log.warning("Can't get hostname", e);
       return "unknown";
     }
   }
   return res;
 }
Exemplo n.º 15
0
  /**
   * Returns the name of the localhost. If that cannot be found it will return <code>localhost
   * </code>.
   *
   * @return my host
   */
  public static String myHost() {
    String str = null;
    try {
      InetAddress inetA = InetAddress.getLocalHost();
      str = inetA.getHostName();
    } catch (UnknownHostException exc) {
    }

    if (str == null) {
      str = "localhost";
    }
    return str;
  }
Exemplo n.º 16
0
  static void test() throws Exception {
    ServerSocketChannel ssc = null;
    SocketChannel sc = null;
    SocketChannel peer = null;
    try {
      ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));

      // loopback connection
      InetAddress lh = InetAddress.getLocalHost();
      sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort()));
      peer = ssc.accept();

      // peer sends message so that "sc" will be readable
      int n = peer.write(ByteBuffer.wrap("Hello".getBytes()));
      assert n > 0;

      sc.configureBlocking(false);

      Selector selector = Selector.open();
      SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

      boolean done = false;
      int failCount = 0;
      while (!done) {
        int nSelected = selector.select();
        if (nSelected > 0) {
          if (nSelected > 1) throw new RuntimeException("More than one channel selected");
          Set<SelectionKey> keys = selector.selectedKeys();
          Iterator<SelectionKey> iterator = keys.iterator();
          while (iterator.hasNext()) {
            key = iterator.next();
            iterator.remove();
            if (key.isWritable()) {
              failCount++;
              if (failCount > 10) throw new RuntimeException("Test failed");
              Thread.sleep(250);
            }
            if (key.isReadable()) {
              done = true;
            }
          }
        }
      }
    } finally {
      if (peer != null) peer.close();
      if (sc != null) sc.close();
      if (ssc != null) ssc.close();
    }
  }
Exemplo n.º 17
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;
 }
Exemplo n.º 18
0
  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());
    }
  }
  /**
   * 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;
  }
Exemplo n.º 20
0
  /**
   * Returns a usable {@link Inet4Address} for the given interface name.
   *
   * <p>If an interface name is given, return the first usable IPv4 address for that interface. If
   * no interface name is given or if that interface doesn't have an IPv4 address, return's
   * localhost address (if IPv4).
   *
   * <p>It is understood this makes the client IPv4 only, but it is important to remember that most
   * BitTorrent extensions (like compact peer lists from trackers and UDP tracker support) are
   * IPv4-only anyway.
   *
   * @param iface The network interface name.
   * @return A usable IPv4 address as a {@link Inet4Address}.
   * @throws UnsupportedAddressTypeException If no IPv4 address was available to bind on.
   */
  private static Inet4Address getIPv4Address(String iface)
      throws SocketException, UnsupportedAddressTypeException, UnknownHostException {
    if (iface != null) {
      Enumeration<InetAddress> addresses = NetworkInterface.getByName(iface).getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress addr = addresses.nextElement();
        if (addr instanceof Inet4Address) {
          return (Inet4Address) addr;
        }
      }
    }

    InetAddress localhost = InetAddress.getLocalHost();
    if (localhost instanceof Inet4Address) {
      return (Inet4Address) localhost;
    }

    throw new UnsupportedAddressTypeException();
  }
Exemplo n.º 21
0
  public LoginBox() {
    super("VnmrJ Login");

    dolayout("", "", "");
    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    // setVast();
    DisplayOptions.addChangeListener(this);

    try {
      InetAddress inetAddress = InetAddress.getLocalHost();
      m_strHostname = inetAddress.getHostName();
    } catch (Exception e) {
      m_strHostname = "localhost";
    }

    VNMRFrame vnmrFrame = VNMRFrame.getVNMRFrame();
    Dimension size = vnmrFrame.getSize();
    position = vnmrFrame.getLocationOnScreen();
    AppIF appIF = Util.getAppIF();
    int h = appIF.statusBar.getSize().height;
    width = size.width;
    height = size.height - h;

    // Allow resizing and use the previous size and position
    // To stop resizing, use setResizable(false);
    readPersistence();

    //        setSize(width, height);
    //        setLocation(position);
    //        setResizable(false);

    setBackgroundColor(Util.getBgColor());

    m_trayTimer =
        new javax.swing.Timer(
            6000,
            new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                setTrays();
              }
            });
  }
Exemplo n.º 22
0
  /*
   * Create an SMTPConnection object. Create the socket and the associated
   * streams. Send HELO-command and check for errors.
   */
  public SMTPConnection(Envelope envelope) throws IOException {
    connection = new Socket(envelope.DestAddr, SMTP_PORT);
    fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    toServer = new DataOutputStream(connection.getOutputStream());

    String reply = fromServer.readLine();
    if (parseReply(reply) != 220) {
      System.out.println("Error in connect.");
      System.out.println(reply);
      return;
    }
    String localhost = (InetAddress.getLocalHost()).getHostName();
    try {
      sendCommand("HELO " + localhost, 250);
    } catch (IOException e) {
      System.out.println("HELO failed. Aborting.");
      return;
    }
    isConnected = true;
  }
Exemplo n.º 23
0
  public void initGroup() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      sendSocket = new DatagramSocket();
      recvSocket = new MulticastSocket(RECV_PORT);
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(GROUP_BROADCAST_ADDR);
      ((MulticastSocket) recvSocket).joinGroup(group);
      // recvAckSocket.joinGroup (group) ;
      localIP = InetAddress.getLocalHost().getHostAddress();

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();

      bGroup = true;
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Exemplo n.º 24
0
  /**
   * @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;
    }
  }
Exemplo n.º 25
0
  public void init() throws MQClientException {
    nameServer = PropertyFileUtil.get("rocketmq.namesrv.domain");

    if (StringUtils.isBlank(nameServer)) {

      logger.warn("【MQ init】property rocketmq.namesrv.domain not found");

      return;
    }

    if ("localTest".equals(nameServer)) {

      logger.warn("【MQ init】localTest");

      return;
    }

    if (StringUtils.isBlank(System.getProperty("rocketmq.namesrv.domain"))) {
      System.setProperty("rocketmq.namesrv.domain", nameServer);
    }
    topicType = getTopic();
    topic = RocketMqUtils.getTopic(topicType);

    if (StringUtils.isBlank(group)) {
      group = "S_" + topic.getTopic() + "_" + topic.getTags();
    }
    consumer = new DefaultMQPushConsumer(group);
    consumer.setNamesrvAddr(nameServer);
    consumer.setMessageModel(getMessageModel());
    consumer.setConsumeThreadMin(minConsumeThread);
    consumer.setConsumeThreadMax(maxConsumeThread);
    // 可以不设置 设置后可以起多个 消费端
    try {
      consumer.setInstanceName("DEFAULT_CONSUMER-" + InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
      logger.error("getHostName error", e);
    }
    // 设置订阅的topic 设置订阅过滤表达式
    if (StringUtils.isBlank(subExpression)) {
      subExpression = topic.getTags();
      consumer.subscribe(topic.getTopic(), subExpression);
    } else {
      consumer.subscribe(topic.getTopic(), subExpression);
    }
    try {
      consumer.registerMessageListener(this);
      consumer.start();
    } catch (MQClientException e) {
      logger.error(
          "consumer start error!topic={},subExpression={},group={}",
          topic.getTopic(),
          subExpression,
          group,
          e);
    }
    logger.info(
        "consumer start! topic={},subExpression={},group={}",
        topic.getTopic(),
        subExpression,
        group);
  }
Exemplo n.º 26
0
  /**
   * Create UDP sender and receiver sockets. Currently there are 2 sockets (sending and receiving).
   * This is due to Linux's non-BSD compatibility in the JDK port (see DESIGN).
   */
  void createSockets() throws Exception {
    InetAddress tmp_addr = null;

    // bind_addr not set, try to assign one by default. This is needed on Windows

    // changed by bela Feb 12 2003: by default multicast sockets will be bound to all network
    // interfaces

    // CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
    // local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
    // 0.0.0.0:1.2.3.4 (on hostB) would fail !
    if (bind_addr == null) {
      InetAddress[] interfaces =
          InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
      if (interfaces != null && interfaces.length > 0) bind_addr = interfaces[0];
    }

    if (bind_addr == null) bind_addr = InetAddress.getLocalHost();

    if (bind_addr != null && Trace.trace) {
      Trace.info(
          "UDP.createSockets()",
          "unicast sockets will use interface " + bind_addr.getHostAddress());

      // 2. Create socket for receiving unicast UDP packets. The address and port
      //    of this socket will be our local address (local_addr)

      // 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
    }
    int rcv_port = bind_port, max_port = bind_port + port_range;
    while (rcv_port <= max_port) {

      try {
        sock = new DatagramSocket(rcv_port, bind_addr);
        break;
      } catch (SocketException bind_ex) { // Cannot listen on this port
        rcv_port++;
      } catch (SecurityException sec_ex) { // Not allowed to list on this port
        rcv_port++;
      }

      // Cannot listen at all, throw an Exception
      if (rcv_port == max_port + 1) { // +1 due to the increment above
        throw new Exception(
            "UDP.createSockets(): cannot list on any port in range "
                + bind_port
                + "-"
                + (bind_port + port_range));
      }
    }
    // ucast_recv_sock=new DatagramSocket(bind_port, bind_addr);
    if (sock == null) {
      throw new Exception("UDP.createSocket(): sock is null");
    }

    local_addr = new IpAddress(sock.getLocalAddress(), sock.getLocalPort());
    if (additional_data != null) {
      local_addr.setAdditionalData(additional_data);

      // 3. Create socket for receiving IP multicast packets
    }
    if (ip_mcast) {
      mcast_sock = new MulticastSocket(mcast_port);
      mcast_sock.setTimeToLive(ip_ttl);
      if (bind_addr != null) {
        mcast_sock.setInterface(bind_addr);
      }
      tmp_addr = InetAddress.getByName(mcast_addr_name);
      mcast_addr = new IpAddress(tmp_addr, mcast_port);
      mcast_sock.joinGroup(tmp_addr);
    }

    setBufferSizes();

    if (Trace.trace) {
      Trace.info("UDP.createSockets()", "socket information:\n" + dumpSocketInfo());
    }
  }
Exemplo n.º 27
0
  public static IUmenu mainAE() {
    PerfilesBD coleccion = new PerfilesBD();
    final PerfilesBD perfilesDB = coleccion;
    String ip = "";
    try {
      ip = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception exp) {
    }
    ipServer = ip;
    final String ipDef = ip;
    if (!coleccion.estaMontadoServidor()) {

      new Thread() {
        public void run() {

          try {
            Servidor servidor = new Servidor();
            servidor.ejecutarServidor();
          } catch (Exception e) {
            System.out.println(e);
          }
        }
      }.start();
      /*new Thread()
      {
              public void run()
              {

                      try
                      {
                              ServidorChat servidorChat = new ServidorChat();
                              servidorChat.ejecutarServidor();
                      }
                      catch (Exception e)
                      {
                              System.out.println(e);
                      }
              }
      }.start();*/
      new Thread() {
        public void run() {

          try {
            ClienteAdm clienteAdm = new ClienteAdm(ipDef);
          } catch (Exception e) {
            System.out.println(e);
          }
        }
      }.start();
    }

    String hostOut = coleccion.getHostServidor();

    IUmenu a = new IUmenu(hostOut);
    a.setBounds(120, 70, 800, 600);
    a.setUndecorated(true);
    a.getRootPane().setWindowDecorationStyle(0);
    a.setDefaultCloseOperation(a.DO_NOTHING_ON_CLOSE);
    a.setResizable(false);
    a.setVisible(true);
    menu = a;
    return a;
  }
 /**
  * Creates a default TCP transport mapping with the server for incoming messages disabled.
  *
  * @throws UnknownHostException
  * @throws IOException on failure of binding a local port.
  */
 public DefaultTcpTransportMapping() throws UnknownHostException, IOException {
   super(new TcpAddress(InetAddress.getLocalHost(), 0));
 }
Exemplo n.º 29
0
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Usage: rtpaudio <targetIP> <targetPort>");
      System.exit(0);
    }

    try {
      RegistryDefaults.setDefaultFlags(RegistryDefaults.FMJ);

      // create a clean registry
      RegistryDefaults.unRegisterAll(RegistryDefaults.ALL);
      RegistryDefaults.registerAll(RegistryDefaults.FMJ);

      // remove all capture devices
      Vector deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
      for (int i = 0; i < deviceList.size(); i++) {
        CaptureDeviceInfo cdi = (CaptureDeviceInfo) deviceList.elementAt(i);
        CaptureDeviceManager.removeDevice(cdi);
      }

      // update capture device list
      new net.sf.fmj.media.cdp.javasound.CaptureDevicePlugger().addCaptureDevices();
      PlugInManager.commit();

      deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
      if ((null == deviceList) || (deviceList.size() == 0)) {
        System.out.println("### ERROR found no audio capture device");
        System.exit(0);
      }

      // enumerate all codec
      Vector codecList = PlugInManager.getPlugInList(null, null, PlugInManager.CODEC);
      System.out.println("found " + codecList.size() + " codec");
      for (int i = 0; i < codecList.size(); i++) {
        String aCodecClass = (String) codecList.elementAt(i);
        System.out.println("# " + (i + 1) + " " + aCodecClass);
      }

      // fetch first available audio capture device
      deviceList = (Vector) CaptureDeviceManager.getDeviceList(null).clone();
      CaptureDeviceInfo captureDeviceInfo = (CaptureDeviceInfo) deviceList.elementAt(0);
      System.out.println("### using " + captureDeviceInfo.getName());
      System.out.println("### locator " + captureDeviceInfo.getLocator());

      javax.media.protocol.DataSource dataSource =
          javax.media.Manager.createDataSource(
              new javax.media.MediaLocator(captureDeviceInfo.getLocator().toString()));
      // javax.media.protocol.DataSource dataSource =
      // javax.media.Manager.createDataSource(new
      // javax.media.MediaLocator("javasound://"));
      System.out.println("### created datasource " + dataSource.getClass().getName());

      javax.media.control.FormatControl[] formatControls =
          ((javax.media.protocol.CaptureDevice) dataSource).getFormatControls();
      System.out.println("got format control " + formatControls[0].getClass().getName());

      System.out.println("current format is " + formatControls[0].getFormat());

      // set audio capture format
      javax.media.Format[] formats = formatControls[0].getSupportedFormats();
      for (int i = 0; i < formats.length; i++) {
        javax.media.format.AudioFormat af = (javax.media.format.AudioFormat) formats[i];
        if ((af.getChannels() == 1) && (af.getSampleSizeInBits() == 16)) {
          if (af.getSampleRate() == Format.NOT_SPECIFIED) {
            javax.media.format.AudioFormat newAudioFormat =
                new javax.media.format.AudioFormat(
                    af.getEncoding(),
                    8000.0f,
                    javax.media.Format.NOT_SPECIFIED,
                    javax.media.Format.NOT_SPECIFIED);
            // javax.media.format.AudioFormat newAudioFormat = new
            // javax.media.format.AudioFormat(af.getEncoding(),
            // 44100.0f, javax.media.Format.NOT_SPECIFIED,
            // javax.media.Format.NOT_SPECIFIED);
            formatControls[0].setFormat(newAudioFormat.intersects(af));
            break;
          }
        }
      }
      System.out.println("current format is now " + formatControls[0].getFormat());

      FrameProcessingControl fpc = null;

      // adujst recording buffer ( to adjust latency )
      dataSource.stop();
      Object[] controls = dataSource.getControls();
      for (int i = 0; i < controls.length; i++) {
        String className = controls[i].getClass().getName();
        if (-1 != className.indexOf("JavaSoundBufferControl")) {
          javax.media.control.BufferControl bc = (javax.media.control.BufferControl) controls[i];
          System.out.println(
              "### current javasound buffer length is " + bc.getBufferLength() + " ms");
          bc.setBufferLength(40);
          System.out.println(
              "### current javasound buffer length is " + bc.getBufferLength() + " ms");
        } else if (-1 != className.indexOf("JitterBufferControl")) {
          javax.media.control.BufferControl bc = (javax.media.control.BufferControl) controls[i];
          System.out.println("### current jitter buffer length is " + bc.getBufferLength() + " ms");
          bc.setBufferLength(80);
          System.out.println("### current jitter buffer length is " + bc.getBufferLength() + " ms");
        } else if (-1 != className.indexOf("FPC")) {
          fpc = (FrameProcessingControl) controls[i];
          System.out.println("### found bitrate control " + fpc.getClass());
        }
      }
      dataSource.start();

      // create processor
      javax.media.Processor processor = javax.media.Manager.createProcessor(dataSource);
      System.out.println("### created processor " + processor.getClass().getName());

      processor.configure();
      for (int idx = 0; idx < 100; idx++) {
        if (processor.getState() == Processor.Configured) {
          break;
        }
        Thread.sleep(100);
      }
      System.out.println("### processor state " + processor.getState());

      processor.setContentDescriptor(
          new javax.media.protocol.ContentDescriptor(ContentDescriptor.RAW_RTP));

      javax.media.control.TrackControl[] tracks = processor.getTrackControls();
      // /tracks[0].setFormat(new
      // javax.media.format.AudioFormat(javax.media.format.AudioFormat.ULAW_RTP,
      // 8000, 8, 1));
      tracks[0].setFormat(
          new javax.media.format.AudioFormat(javax.media.format.AudioFormat.GSM_RTP, 8000, 8, 1));

      processor.realize();
      for (int idx = 0; idx < 100; idx++) {
        if (processor.getState() == Controller.Realized) {
          break;
        }
        Thread.sleep(100);
      }
      System.out.println("### processor state " + processor.getState());

      javax.media.protocol.DataSource dataOutput = processor.getDataOutput();
      System.out.println("### processor data output " + dataOutput.getClass().getName());

      // BitRateControl
      BitRateControl bitrateControl = null;

      Object[] controls2 = dataOutput.getControls();
      for (int i = 0; i < controls2.length; i++) {
        if (controls2[i] instanceof BitRateControl) {
          bitrateControl = (BitRateControl) controls2[i];
          System.out.println("### found bitrate control " + bitrateControl.getClass());
          break;
        }
      }

      // PacketSizeControl
      Object[] controls3 = processor.getControls();
      for (int i = 0; i < controls3.length; i++) {
        if (controls3[i] instanceof PacketSizeControl) {
          PacketSizeControl psc = (PacketSizeControl) controls3[i];
          System.out.println("### current packetsize is " + psc.getPacketSize() + " bytes");
          psc.setPacketSize(66);
          System.out.println("### current packetsize is " + psc.getPacketSize() + " bytes");
          break;
        }
      }

      // enumerate all controls of the processor
      Object[] pcontrols = processor.getControls();
      for (int i = 0; i < pcontrols.length; i++) {
        System.out.println("processor control " + i + " " + pcontrols[i]);
      }

      javax.media.rtp.RTPManager rtpManager = javax.media.rtp.RTPManager.newInstance();

      javax.media.rtp.SessionAddress local =
          new javax.media.rtp.SessionAddress(
              InetAddress.getLocalHost(), Integer.valueOf(args[1]).intValue());
      javax.media.rtp.SessionAddress target =
          new javax.media.rtp.SessionAddress(
              InetAddress.getByName(args[0]), Integer.valueOf(args[1]).intValue());

      rtpManager.initialize(local);
      rtpManager.addTarget(target);

      javax.media.rtp.SendStream sendStream = rtpManager.createSendStream(dataOutput, 0);
      sendStream.start();

      processor.start();
      Thread.sleep(1000);

      System.out.println("\n>>>>>>  TRANSMITTING ULAW/RTP AUDIO NOW");
      while (2 > 1) {
        Thread.sleep(1000);

        if (null != bitrateControl) {
          TransmissionStats stats = sendStream.getSourceTransmissionStats();
          System.out.println(
              "rtp audio send: bitrate="
                  + bitrateControl.getBitRate()
                  + " (pdu="
                  + stats.getPDUTransmitted()
                  + " bytes="
                  + stats.getBytesTransmitted()
                  + " overrun="
                  + fpc.getFramesDropped()
                  + ")");
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    System.exit(0);
  }
Exemplo n.º 30
0
  /**
   * Provides the default host name that will be proposed to the user for the local host.
   *
   * @return the default host name that will be proposed to the user for the local host.
   */
  public static String getDefaultHostName() {
    if (defaultHostName == null) {
      // Run a thread in the background in order to avoid blocking the
      // application if reverse DNS lookups take a long time.
      final CountDownLatch latch = new CountDownLatch(1);
      Thread t =
          new Thread(
              new Runnable() {
                /**
                 * Search for a host name of the form host.example.com on each interface, except the
                 * loop back. Prefer interfaces of the form ethX.
                 */
                public void run() {
                  try {
                    SortedMap<String, String> hostNames = new TreeMap<>();
                    Enumeration<NetworkInterface> i = NetworkInterface.getNetworkInterfaces();
                    while (i.hasMoreElements()) {
                      NetworkInterface n = i.nextElement();

                      // Skip loop back interface.
                      if (n.isLoopback()) {
                        continue;
                      }

                      // Check each interface address (IPv4 and IPv6).
                      String ipv4HostName = null;
                      String ipv6HostName = null;
                      Enumeration<InetAddress> j = n.getInetAddresses();
                      while (j.hasMoreElements()) {
                        InetAddress address = j.nextElement();
                        String hostAddress = address.getHostAddress();
                        String hostName = address.getCanonicalHostName();

                        // Ignore hostnames which are IP addresses.
                        if (!hostAddress.equals(hostName)) {
                          if (address instanceof Inet4Address) {
                            ipv4HostName = hostName;
                          } else if (address instanceof Inet6Address) {
                            ipv6HostName = hostName;
                          }
                        }
                      }

                      // Remember the host name if it looks fully qualified.
                      String fqHostName = null;
                      if (ipv4HostName != null && ipv4HostName.contains(".")) {
                        fqHostName = ipv4HostName;
                      } else if (ipv6HostName != null && ipv6HostName.contains(".")) {
                        fqHostName = ipv6HostName;
                      }

                      if (fqHostName != null) {
                        hostNames.put(n.getName(), fqHostName);

                        // This looks like a fully qualified name on a ethX interface,
                        // so
                        // use that and break out.
                        if (n.getName().startsWith("eth")) {
                          defaultHostName = fqHostName;
                          break;
                        }
                      }
                    }

                    if (defaultHostName == null && !hostNames.isEmpty()) {
                      // No ethX host name, so try any other host name that was found.
                      defaultHostName = hostNames.values().iterator().next();
                    }
                  } catch (Exception e) {
                    // Ignore - we'll default to the loopback address later.
                  }

                  latch.countDown();
                }
              });

      try {
        t.setDaemon(true);
        t.start();
        latch.await(1, TimeUnit.SECONDS);
      } catch (Exception e) {
        // Ignore - we'll default to the loopback address later.
      }

      if (defaultHostName == null) {
        // No host names found, so use the loop back.
        try {
          defaultHostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
          // Not much we can do here.
          defaultHostName = "localhost";
        }
      }
    }
    return defaultHostName;
  }