Java Code Examples for java.net.Socket.getInetAddress()

The following are Jave code examples for showing how to use getInetAddress() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: TrustManagerExt.java   Source Code and License Vote up 6 votes
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
    Socket socket) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (socket != null && socket.isConnected()
      && socket instanceof SSLSocket) {
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
      ip = inetAddress.getHostAddress();
    }
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkClientTrusted(chain, authType, socket);
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: TrustManagerExt.java   Source Code and License Vote up 6 votes
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType,
    Socket socket) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (socket != null && socket.isConnected()
      && socket instanceof SSLSocket) {
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
      ip = inetAddress.getHostAddress();
    }
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkServerTrusted(chain, authType, socket);
}
 
Example 3
Project: io-command   File: ServerListenClientRunner.java   Source Code and License Vote up 6 votes
@Override
public void run() {
    while(isRunning) {
        if (serverSocket.isClosed()) {
            isRunning = false;
            break;
        }
        
        try {
        	// server 端卡在这里当有  client 发起连接的时候才会继续运行, 每个连接创建一个  ConnectionThread 对象
        	// 每个 ConnectionThread 对象处理一个 Client
            Socket socket = serverSocket.accept();
            InetAddress remoteClient = socket.getInetAddress();
            
            ClientInfo clientInfo = new ClientInfo(socket, remoteClient.getHostName(), remoteClient.getHostAddress(), socket.getPort(), System.currentTimeMillis());
            
            logger.info("incoming remote client, remoteClientInfo = {}", clientInfo.getClientInfo());
            Future<String> clientFuture = ThreadService.getHandleClientService().submit(new ServerHandleClientConnectionRunner(clientInfo, handlerMap));
            
            clientResultList.add(new ClientFutureInfo(clientInfo, clientFuture));
            
        } catch (IOException e) {
        	logger.error("ListeningThread.run has error", e);
        }
    }
}
 
Example 4
Project: L2J-Global   File: MMOConnection.java   Source Code and License Vote up 6 votes
public MMOConnection(SelectorThread<T> selectorThread, Socket socket, SelectionKey key, boolean tcpNoDelay)
{
	_selectorThread = selectorThread;
	_socket = socket;
	_address = socket.getInetAddress();
	_readableByteChannel = socket.getChannel();
	_writableByteChannel = socket.getChannel();
	_port = socket.getPort();
	_selectionKey = key;
	
	_sendQueue = new NioNetStackList<>();
	
	try
	{
		_socket.setTcpNoDelay(tcpNoDelay);
	}
	catch (SocketException e)
	{
		e.printStackTrace();
	}
}
 
Example 5
Project: fdt   File: ControlChannel.java   Source Code and License Vote up 6 votes
/**
 * A remote peer connected to FDT
 *
 * @param s - the socket
 * @throws Exception - if anything goes wrong in intialization
 */
public ControlChannel(Socket s, ControlChannelNotifier notifier) throws Exception {
    try {
        this.controlSocket = s;

        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();

        this.notifier = notifier;

        initStreams();
        controlSocket.setTcpNoDelay(true);
        controlSocket.setSoTimeout(1000);

    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 6
Project: fdt   File: ServerSessionManager.java   Source Code and License Vote up 6 votes
public ServerSessionManager(Socket s) throws Exception {
    currentFile = local.getHomeDirectory();
    this.currentDir = currentFile.getAbsolutePath();
    osName = System.getProperty("os.name");
    userDir = System.getProperty("user.home");
    fileSeparator = System.getProperty("file.separator");
    update();
    try {
        this.controlSocket = s;
        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();
        initStreams();
        controlSocket.setSoTimeout(1000);
    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 7
Project: L2jBrasil   File: MMOConnection.java   Source Code and License Vote up 5 votes
public MMOConnection(final SelectorThread<T> selectorThread, final Socket socket, final SelectionKey key)
{
    _selectorThread = selectorThread;
    _socket = socket;
    _address = socket.getInetAddress();
    _readableByteChannel = socket.getChannel();
    _writableByteChannel = socket.getChannel();
    _port = socket.getPort();
    _selectionKey = key;

    _sendQueue = new NioNetStackList<SendablePacket<T>>();
}
 
Example 8
Project: L2jBrasil   File: LoginStatusThread.java   Source Code and License Vote up 5 votes
private static boolean isValidIP(Socket client) {
	boolean result = false;
	InetAddress ClientIP = client.getInetAddress();

	// convert IP to String, and compare with list
	String clientStringIP = ClientIP.getHostAddress();

	telnetOutput(1, "Connection from: "+clientStringIP);

	// read and loop thru list of IPs, compare with newIP
	if ( Config.DEVELOPER ) telnetOutput(2, "");

	try {
		Properties telnetSettings = new Properties();
		InputStream telnetIS = new FileInputStream(new File(Config.TELNET_FILE));
		telnetSettings.load(telnetIS);
		telnetIS.close();

		String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost");

		if ( Config.DEVELOPER ) telnetOutput(3, "Comparing ip to list...");

		// compare
		String ipToCompare = null;
		for (String ip:HostList.split(",")) {
			if ( !result ) {
				ipToCompare = InetAddress.getByName(ip).getHostAddress();
				if ( clientStringIP.equals(ipToCompare) ) result = true;
				if ( Config.DEVELOPER ) telnetOutput(3, clientStringIP + " = " + ipToCompare + "("+ip+") = " + result);
			}
		}
	}
	catch ( IOException e) {
		if ( Config.DEVELOPER ) telnetOutput(4, "");
		telnetOutput(1, "Error: "+e);
	}

	if ( Config.DEVELOPER ) telnetOutput(4, "Allow IP: "+result);
	return result;
}
 
Example 9
Project: L2jBrasil   File: GameStatusThread.java   Source Code and License Vote up 5 votes
private boolean isValidIP(Socket client) {
    boolean result = false;
    InetAddress ClientIP = client.getInetAddress();

    // convert IP to String, and compare with list
    String clientStringIP = ClientIP.getHostAddress();

    telnetOutput(1, "Connection from: "+clientStringIP);

    // read and loop thru list of IPs, compare with newIP
    if ( Config.DEVELOPER ) telnetOutput(2, "");

    try {
        Properties telnetSettings = new Properties();
        InputStream telnetIS = new FileInputStream(new File(Config.TELNET_FILE));
        telnetSettings.load(telnetIS);
        telnetIS.close();

        String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost");

        if ( Config.DEVELOPER ) telnetOutput(3, "Comparing ip to list...");

        // compare
        String ipToCompare = null;
        for (String ip:HostList.split(",")) {
            if ( !result ) {
                ipToCompare = InetAddress.getByName(ip).getHostAddress();
                if ( clientStringIP.equals(ipToCompare) ) result = true;
                if ( Config.DEVELOPER ) telnetOutput(3, clientStringIP + " = " + ipToCompare + "("+ip+") = " + result);
            }
        }
    }
    catch ( IOException e) {
        if ( Config.DEVELOPER ) telnetOutput(4, "");
        telnetOutput(1, "Error: "+e);
    }

    if ( Config.DEVELOPER ) telnetOutput(4, "Allow IP: "+result);
    return result;
}
 
Example 10
Project: xdman   File: SocketClient.java   Source Code and License Vote up 5 votes
/**
 * Verifies that the remote end of the given socket is connected to the
 * the same host that the SocketClient is currently connected to.  This
 * is useful for doing a quick security check when a client needs to
 * accept a connection from a server, such as an FTP data connection or
 * a BSD R command standard error stream.
 * <p>
 * @return True if the remote hosts are the same, false if not.
 */
public boolean verifyRemote(Socket socket)
{
    InetAddress host1, host2;

    host1 = socket.getInetAddress();
    host2 = getRemoteAddress();

    return host1.equals(host2);
}
 
Example 11
Project: javase   File: Server.java   Source Code and License Vote up 5 votes
public ClientHandler(Socket socket) {
	this.socket = socket;
	/*
	 * 通过Socket获取远程计算机地址信息 对于服务端而言,远程计算机就是客户端了
	 */
	InetAddress address = socket.getInetAddress();
	// 获取IP地址
	host = address.getHostAddress();
}
 
Example 12
Project: alfresco-greenmail   File: SmtpConnection.java   Source Code and License Vote up 5 votes
public SmtpConnection(SmtpHandler handler, Socket sock)
        throws IOException {
    this.sock = sock;
    sock.setSoTimeout(TIMEOUT_MILLIS);
    clientAddress = sock.getInetAddress();
    OutputStream o = sock.getOutputStream();
    InputStream i = sock.getInputStream();
    out = new InternetPrintWriter(o, true);
    in = new BufferedReader(new InputStreamReader(i));

    this.handler = handler;
}
 
Example 13
Project: freecol   File: FreeColServer.java   Source Code and License Vote up 5 votes
/**
 * Add a new user connection.  That is a new connection to the server
 * that has not yet logged in as a player.
 *
 * @param socket The client {@code Socket} the connection arrives on.
 * @exception IOException if the socket was already broken.
 */
public void addNewUserConnection(Socket socket) throws IOException {
    final String name = socket.getInetAddress() + ":" + socket.getPort();
    Connection c = new Connection(socket, FreeCol.SERVER_THREAD + name)
        .setMessageHandler(this.userConnectionHandler);
    getServer().addConnection(c);
    // Short delay here improves reliability
    Utils.delay(100, "New connection delay interrupted");
    c.send(new GameStateMessage(this.serverState));
    if (this.serverState == ServerState.IN_GAME) {
        c.send(new VacantPlayersMessage().setVacantPlayers(getGame()));
    }
    logger.info("Client connected from " + name);
}
 
Example 14
Project: fdt   File: XDRTcpSocket.java   Source Code and License Vote up 5 votes
public XDRTcpSocket(Socket s) throws IOException {
      super("XDRTcpSocket for [ " + s.getInetAddress() + ":" + s.getPort() + " ] ", new XDROutputStream(s.getOutputStream()), new XDRInputStream(s.getInputStream()));
      this.rawSocket = s;
      closed = false;
/*this.mode = mode;
this.auth = auth;*/
  }
 
Example 15
Project: FreeCol   File: FreeColServer.java   Source Code and License Vote up 5 votes
/**
 * Add a new user connection.  That is a new connection to the server
 * that has not yet logged in as a player.
 *
 * @param socket The client {@code Socket} the connection arrives on.
 * @exception IOException if the socket was already broken.
 */
public void addNewUserConnection(Socket socket) throws IOException {
    final String name = socket.getInetAddress() + ":" + socket.getPort();
    Connection c = new Connection(socket, FreeCol.SERVER_THREAD + name)
        .setMessageHandler(this.userConnectionHandler);
    getServer().addConnection(c);
    // Short delay here improves reliability
    Utils.delay(100, "New connection delay interrupted");
    c.send(new GameStateMessage(this.serverState));
    if (this.serverState == ServerState.IN_GAME) {
        c.send(new VacantPlayersMessage().setVacantPlayers(getGame()));
    }
    logger.info("Client connected from " + name);
}
 
Example 16
Project: SocketGames   File: GameServer.java   Source Code and License Vote up 4 votes
/**
 * Opens a server port to listen for incoming network requests. When a request
 * is received, accepts the connection, wraps the resulting socket in a thread,
 * and starts the thread process.
 * 
 * @param args[0]
 *            the port to use when listening for connections; if no command line
 *            arguments are provided, uses the default
 * @param args[1]
 *            the max number of concurrent connections to accept; if no command
 *            line arguments, uses the default
 * @throws java.io.IOException
 *             if unable to read from socket
 */
public static void main(String[] args) throws IOException {
	int desiredPort = DEFAULT_PORT_NUM;
	int maxConnections = DEFAULT_MAX_USERS;
	boolean createLogFile = false;
	try {
		desiredPort = Integer.parseInt(args[0]);
		maxConnections = Integer.parseInt(args[1]);
		createLogFile = Boolean.parseBoolean(args[2]);
	} catch (ArrayIndexOutOfBoundsException
			| NumberFormatException e) {
		LOGGER.info(
				"Command line arguments missing or faulty.  Launching with program defaults.");
	} 
	if (createLogFile) attachLogFileHandler();
	String refuseNewConnectionMessage = "The server limit of " + maxConnections
			+ ((maxConnections == 1) ? " connection"
					: " connections")
			+ " has been reached.  Please try again, later.";

	try (ServerSocket socketRequestListener = new ServerSocket(
			desiredPort)) {
		LOGGER.info("GameServer started on port: "
				+ socketRequestListener.getLocalPort()
				+ ".  Maximum simultaneous users: "
				+ maxConnections);
		GameTracker.initialize();
		while (true) {
			// the following call blocks until a connection is made
			Socket socket = socketRequestListener.accept();
			InetAddress remoteMachine = socket.getInetAddress();
			// String remoteHost = remoteMachine.getHostName();
			LOGGER.info("Incoming connection request from " + remoteMachine);

			int numActiveSockets = Thread.activeCount() - 1;
			if (numActiveSockets < maxConnections) {
				new Thread(new GameThread(socket)).start();
				numActiveSockets++;
				LOGGER.info("HELLO " + remoteMachine
						+ ".  Number of current connections: "
						+ numActiveSockets);
			} else {
				PrintWriter out = new PrintWriter(
						socket.getOutputStream());
				out.println(refuseNewConnectionMessage);
				out.close();
				socket.close();
				LOGGER.warning("SORRY " + remoteMachine
						+ ".  Number of current connections: "
						+ numActiveSockets);
			}
		}
	}
}
 
Example 17
Project: java-android-websocket-client   File: BHttpConnectionBase.java   Source Code and License Vote up 4 votes
@Override
public InetAddress getRemoteAddress() {
    final Socket socket = this.socketHolder.get();
    return socket != null ? socket.getInetAddress() : null;
}
 
Example 18
Project: CrypDist   File: ReceiveHeartBeat.java   Source Code and License Vote up 4 votes
public void run() {
    while (true) {
        try {
            ServerSocket heartBeatSocket = new ServerSocket(client.getHeartBeatPort());
            Socket hb = heartBeatSocket.accept();
            heartBeatSocket.close();

            DataInputStream in = new DataInputStream(hb.getInputStream());
            int flag = in.readInt();


            if(flag != Config.HEARTBEAT_FLAG_SERVER && flag != Config.HEARTBEAT_FLAG_CLIENT) {
                hb.close();
                return;
            }


            if(flag == Config.HEARTBEAT_FLAG_CLIENT) {
                int hbPort = in.readInt();
                int swPort = in.readInt();

                InetAddress addr = hb.getInetAddress();

                boolean b = true;
                for(Peer p: client.peerList.keySet()) {
                    if (p.getAddress().equals(addr)) {
                        b = false;
                        break;
                    }
                }
                if (b) {
                    Peer x = new Peer(addr,hbPort,swPort);
                    log.info("New peer added.");
                    client.peerList.put(x,0);
                }
            }

            DataOutputStream out = new DataOutputStream(hb.getOutputStream());
            out.writeInt(Config.HEARTBEAT_ACK);
            out.flush();

            hb.close();
        }
        catch (SocketTimeoutException s) {
            log.warn("Server socket timed out!");
            log.warn(s);
        } catch (IOException e) {
            log.warn("IOException while receiving server request!");
            log.warn(e);
        }
    }
}
 
Example 19
Project: kafka-0.11.0.0-src-with-comment   File: KafkaChannel.java   Source Code and License Vote up 4 votes
public String socketDescription() {
    Socket socket = transportLayer.socketChannel().socket();
    if (socket.getInetAddress() == null)
        return socket.getLocalAddress().toString();
    return socket.getInetAddress().toString();
}
 
Example 20
Project: Lamp   File: SocketTransceiver.java   Source Code and License Vote up 2 votes
/**
 * 实例化
 *
 * @param socket 已经建立连接的socket
 */
public SocketTransceiver(Socket socket) {
    this.socket = socket;
    this.addr = socket.getInetAddress();
}