Exemplo n.º 1
1
  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);
  }
Exemplo n.º 2
0
  // Check if the datagramsocket adaptor can send with a packet
  // that has not been initialized with an address; the legacy
  // datagram socket will send in this case
  private static void test2() throws Exception {
    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    byte b[] = "hello".getBytes("UTF-8");
    DatagramPacket pkt = new DatagramPacket(b, b.length);
    sndChannel.socket().send(pkt);

    ByteBuffer bb = ByteBuffer.allocate(256);
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    // Check that the pkt got set with the target address;
    // This is legacy behavior
    if (!pkt.getSocketAddress().equals(receiver)) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Exemplo n.º 3
0
  // Check if DatagramChannel.send while connected can include
  // address without throwing
  private static void test1() throws Exception {

    DatagramChannel sndChannel = DatagramChannel.open();
    sndChannel.socket().bind(null);
    InetSocketAddress sender =
        new InetSocketAddress(InetAddress.getLocalHost(), sndChannel.socket().getLocalPort());

    DatagramChannel rcvChannel = DatagramChannel.open();
    rcvChannel.socket().bind(null);
    InetSocketAddress receiver =
        new InetSocketAddress(InetAddress.getLocalHost(), rcvChannel.socket().getLocalPort());

    rcvChannel.connect(sender);
    sndChannel.connect(receiver);

    ByteBuffer bb = ByteBuffer.allocate(256);
    bb.put("hello".getBytes());
    bb.flip();
    int sent = sndChannel.send(bb, receiver);
    bb.clear();
    rcvChannel.receive(bb);
    bb.flip();
    CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
    if (!cb.toString().startsWith("h")) throw new RuntimeException("Test failed");

    rcvChannel.close();
    sndChannel.close();
  }
Exemplo n.º 4
0
  /**
   * Attempts to log a client in using the authentication server. Authentication server needs to run
   * on the same host as the file server.
   *
   * @throws IOException Error reading from socket.
   */
  private void login() throws IOException {
    // set up required variables
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress authServerIP =
        InetAddress
            .getLocalHost(); // because authentication server runs on same host as file server
    byte[] dataToSend;
    byte[] receivedData = new byte[BUFFER_SIZE];

    // get username and password
    String userName = inFromClient.readLine().trim(); // get username
    String password = inFromClient.readLine().trim(); // get password
    dataToSend = new String(userName + " " + password).getBytes();

    // send the username and password for processing by authentication server
    DatagramPacket packetToSend =
        new DatagramPacket(dataToSend, dataToSend.length, authServerIP, AUTHENTICATION_PORT);
    clientSocket.send(packetToSend);

    // receive the response from the authentication server
    DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
    clientSocket.receive(receivedPacket);
    String receivedString = new String(receivedPacket.getData()).trim();
    receivedData = receivedString.getBytes();
    if (receivedString.equals("yes")) {
      outToClient.writeBytes(receivedString); // successful login
    } else {
      outToClient.writeBytes("no"); // unsuccessful login
    }
  }
Exemplo n.º 5
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();
  }
Exemplo n.º 6
0
  /*========================================================================*/
  public void init() {
    /*========================================================================*/
    final int port = 9901;

    initComponents();
    try {
      /*-----------------------------------*/
      /* Setup the socket's target address */
      /*-----------------------------------*/
      // InetAddress address = InetAddress.getByName("localhost");//local
      InetAddress address = InetAddress.getLocalHost(); // local
      System.out.println("Local host: " + address.toString());
      Socket socket = new Socket(address, port);

      /*--------------------------------*/
      /* Setup the input/output streams */
      /*--------------------------------*/
      OutputStream os = socket.getOutputStream();
      dos = new DataOutputStream(os);
      InputStream is = socket.getInputStream();
      dis = new DataInputStream(is);
      System.out.println("Setup for all streams complete");

    } catch (IOException ioe) {
      System.out.println("Error connecting");
    }
  }
Exemplo n.º 7
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.º 8
0
 /**
  * 获取本机ip
  *
  * @return
  */
 public static String GetIpAdd() {
   try {
     return InetAddress.getLocalHost().getHostAddress();
   } catch (UnknownHostException e) { // TODO 自动生成 catch 块
     return e.getMessage(); // e.printStackTrace();
   }
 }
  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.º 10
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.º 11
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());
    }
  }
  /** 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.º 13
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.º 14
0
 public InetAddress localHost() {
   try {
     return InetAddress.getLocalHost();
   } catch (UnknownHostException e) {
     return null;
   }
 }
Exemplo n.º 15
0
 public static String ip() {
   try {
     return InetAddress.getLocalHost().getHostAddress();
   } catch (UnknownHostException e) {
     e.printStackTrace();
     return null;
   }
 }
Exemplo n.º 16
0
 public static void main(String[] args) {
   try {
     host = InetAddress.getLocalHost();
   } catch (UnknownHostException e) {
     System.out.println("Host ID not found!");
     System.exit(1);
   }
   userProgram();
 }
 // constructor
 public GameClient_(JFrame oldWindow, MultiPlayerMenuWindow multiPlayerMenu, boolean localHost) {
   m_MultiPlayerMenu = multiPlayerMenu;
   m_OldWindow = oldWindow;
   try {
     m_IP = InetAddress.getLocalHost().getHostAddress();
   } catch (UnknownHostException e) {
     System.err.println(e);
   }
   m_Port = 8000;
 }
Exemplo n.º 18
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.º 19
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.º 20
0
 /** 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;
 }
Exemplo n.º 21
0
 /** Return the hostname of the local machine. */
 public static String getLocalHost() {
   String hostname = null;
   try {
     InetAddress ia = InetAddress.getLocalHost();
     hostname = ia.getHostName();
   } catch (UnknownHostException e) {
     return "localhost";
   }
   return hostname;
 }
Exemplo n.º 22
0
  /** Attach to the specified address with optional attach and handshake timeout. */
  public Connection attach(String address, long attachTimeout, long handshakeTimeout)
      throws IOException {

    if (address == null) {
      throw new NullPointerException("address is null");
    }
    if (attachTimeout < 0 || handshakeTimeout < 0) {
      throw new IllegalArgumentException("timeout is negative");
    }

    int splitIndex = address.indexOf(':');
    String host;
    String portStr;
    if (splitIndex < 0) {
      host = InetAddress.getLocalHost().getHostName();
      portStr = address;
    } else {
      host = address.substring(0, splitIndex);
      portStr = address.substring(splitIndex + 1);
    }

    int port;
    try {
      port = Integer.decode(portStr).intValue();
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("unable to parse port number in address");
    }

    // open TCP connection to VM

    InetSocketAddress sa = new InetSocketAddress(host, port);
    Socket s = new Socket();
    try {
      s.connect(sa, (int) attachTimeout);
    } catch (SocketTimeoutException exc) {
      try {
        s.close();
      } catch (IOException x) {
      }
      throw new TransportTimeoutException("timed out trying to establish connection");
    }

    // handshake with the target VM
    try {
      handshake(s, handshakeTimeout);
    } catch (IOException exc) {
      try {
        s.close();
      } catch (IOException x) {
      }
      throw exc;
    }

    return new SocketConnection(s);
  }
Exemplo n.º 23
0
 /** Copy the new fsimage into the NameNode */
 private void putFSImage(CheckpointSignature sig) throws IOException {
   String fileid =
       "putimage=1&port="
           + infoPort
           + "&machine="
           + InetAddress.getLocalHost().getHostAddress()
           + "&token="
           + sig.toString();
   LOG.info("Posted URL " + fsName + fileid);
   TransferFsImage.getFileClient(fsName, fileid, (File[]) null, false);
 }
Exemplo n.º 24
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;
  }
 // constructor
 public GameClient_(JFrame oldWindow, MultiPlayerMenuWindow multiPlayerMenu) {
   m_MultiPlayerMenu = multiPlayerMenu;
   m_OldWindow = oldWindow;
   try {
     m_IP = InetAddress.getLocalHost().getHostAddress();
     JOptionPane.showMessageDialog(oldWindow, "Server's IP: " + m_IP);
   } catch (UnknownHostException e) {
     System.err.println(e);
   }
   m_Port = 8000;
 }
Exemplo n.º 26
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.º 27
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.º 28
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.º 29
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.º 30
0
  public static void setup() throws Exception {
    client = DatagramChannel.open();
    server = DatagramChannel.open();

    client.socket().bind((SocketAddress) null);
    server.socket().bind((SocketAddress) null);

    client.configureBlocking(false);
    server.configureBlocking(false);

    InetAddress address = InetAddress.getLocalHost();
    int port = client.socket().getLocalPort();
    isa = new InetSocketAddress(address, port);
  }