Java Code Examples for java.net.Socket#getRemoteSocketAddress()

The following examples show how to use java.net.Socket#getRemoteSocketAddress() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: sockslib   File: SocksSession.java    License: Apache License 2.0 6 votes vote down vote up
public SocksSession(long id, Socket socket, Map<Long, Session> sessions) {
  if (!socket.isConnected()) {
    throw new IllegalArgumentException("Socket should be a connected socket");
  }
  if (socket instanceof MonitorSocketWrapper) {
    networkMonitor = new NetworkMonitor();
    ((MonitorSocketWrapper) socket).addMonitor(networkMonitor);
  }
  this.id = id;
  this.socket = socket;
  this.sessions = sessions;
  try {
    this.inputStream = this.socket.getInputStream();
    this.outputStream = this.socket.getOutputStream();
  } catch (IOException e) {
    logger.error(e.getMessage(), e);
  }
  clientAddress = socket.getRemoteSocketAddress();

  attributes = new HashMap<Object, Object>();
}
 
Example 2
@Override
public String toString() {
    final Socket socket = this.socketHolder.get();
    if (socket != null) {
        final StringBuilder buffer = new StringBuilder();
        final SocketAddress remoteAddress = socket.getRemoteSocketAddress();
        final SocketAddress localAddress = socket.getLocalSocketAddress();
        if (remoteAddress != null && localAddress != null) {
            NetUtils.formatAddress(buffer, localAddress);
            buffer.append("<->");
            NetUtils.formatAddress(buffer, remoteAddress);
        }
        return buffer.toString();
    } else {
        return "[Not bound]";
    }
}
 
Example 3
/**
 * @param sock Socket.
 * @throws IOException To break connection.
 */
@SuppressWarnings("SuspiciousMethodCalls")
private void assertNotFailedNode(Socket sock) throws IOException {
    if (forceFailConnectivity && getLocalNode().equals(compromisedNode) && failedAddrs.contains(sock.getRemoteSocketAddress())) {
        log.info(">> Force fail connection " + sock.getRemoteSocketAddress());

        throw new IOException("Force fail connection " + sock.getRemoteSocketAddress());
    }
}
 
Example 4
Source Project: flink   File: BlobServerConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new BLOB connection for a client request.
 *
 * @param clientSocket The socket to read/write data.
 * @param blobServer The BLOB server.
 */
BlobServerConnection(Socket clientSocket, BlobServer blobServer) {
	super("BLOB connection for " + clientSocket.getRemoteSocketAddress());
	setDaemon(true);

	this.clientSocket = clientSocket;
	this.blobServer = checkNotNull(blobServer);

	ReadWriteLock readWriteLock = blobServer.getReadWriteLock();

	this.readLock = readWriteLock.readLock();
}
 
Example 5
Source Project: flink   File: BlobServerConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new BLOB connection for a client request.
 *
 * @param clientSocket The socket to read/write data.
 * @param blobServer The BLOB server.
 */
BlobServerConnection(Socket clientSocket, BlobServer blobServer) {
	super("BLOB connection for " + clientSocket.getRemoteSocketAddress());
	setDaemon(true);

	this.clientSocket = clientSocket;
	this.blobServer = checkNotNull(blobServer);

	ReadWriteLock readWriteLock = blobServer.getReadWriteLock();

	this.readLock = readWriteLock.readLock();
}
 
Example 6
Source Project: canal-1.1.3   File: BioSocketChannel.java    License: Apache License 2.0 5 votes vote down vote up
public SocketAddress getRemoteSocketAddress() {
    Socket socket = this.socket;
    if (socket != null) {
        return socket.getRemoteSocketAddress();
    }

    return null;
}
 
Example 7
Source Project: mireka   File: PrivateTlsConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SSLSocket createSSLSocket(Socket socket) throws IOException {
    if (!enabled)
        throw new IllegalStateException();

    InetSocketAddress remoteAddress =
            (InetSocketAddress) socket.getRemoteSocketAddress();
    SSLSocket sslSocket =
            (SSLSocket) socketFactory.createSocket(socket,
                    remoteAddress.getHostName(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    return sslSocket;
}
 
Example 8
Source Project: redis-rdb-cli   File: XEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
public String address(Socket socket) {
    Objects.requireNonNull(socket);
    InetSocketAddress ra = (InetSocketAddress) socket.getRemoteSocketAddress();
    StringBuilder builder = new StringBuilder();
    builder.append("[ra=");
    if (ra != null) {
        builder.append(ra.toString());
    } else {
        builder.append("N/A");
    }
    builder.append("]");
    return builder.toString();
}
 
Example 9
/**
 * {@inheritDoc}
 */
public InetSocketAddress getRemoteAddress() {
    if (channel == null) {
        return null;
    }

    Socket socket = getSocket();

    if (socket == null) {
        return null;
    }

    return (InetSocketAddress) socket.getRemoteSocketAddress();
}
 
Example 10
Source Project: crate   File: MockTcpTransport.java    License: Apache License 2.0 5 votes vote down vote up
private void readMessage(MockChannel mockChannel, StreamInput input) throws IOException {
    Socket socket = mockChannel.activeChannel;
    byte[] minimalHeader = new byte[TcpHeader.MARKER_BYTES_SIZE];
    int firstByte = input.read();
    if (firstByte == -1) {
        throw new IOException("Connection reset by peer");
    }
    minimalHeader[0] = (byte) firstByte;
    minimalHeader[1] = (byte) input.read();
    int msgSize = input.readInt();
    if (msgSize == -1) {
        socket.getOutputStream().flush();
    } else {
        try (BytesStreamOutput output = new ReleasableBytesStreamOutput(msgSize, bigArrays)) {
            final byte[] buffer = new byte[msgSize];
            input.readFully(buffer);
            output.write(minimalHeader);
            output.writeInt(msgSize);
            output.write(buffer);
            final BytesReference bytes = output.bytes();
            if (TcpTransport.validateMessageHeader(bytes)) {
                InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                messageReceived(bytes.slice(TcpHeader.MARKER_BYTES_SIZE + TcpHeader.MESSAGE_LENGTH_SIZE, msgSize),
                                mockChannel, mockChannel.profile, remoteAddress, msgSize);
            } else {
                // ping message - we just drop all stuff
            }
        }
    }
}
 
Example 11
private static String getConnectionStr(Client client) {
  TTransport transport = client.getInputProtocol().getTransport();
  if (transport instanceof TFramedTransport) {
    TFramedTransport framedTransport = (TFramedTransport) transport;
    transport = framedTransport.getTransport();
  }
  if (transport instanceof TSocket) {
    TSocket tsocket = (TSocket) transport;
    Socket socket = tsocket.getSocket();
    SocketAddress localSocketAddress = socket.getLocalSocketAddress();
    SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
    return localSocketAddress.toString() + ":" + remoteSocketAddress.toString();
  }
  return "unknown";
}
 
Example 12
Source Project: qpid-broker-j   File: TCPTunneler.java    License: Apache License 2.0 5 votes vote down vote up
public StreamForwarder(Socket input,
                       Socket output,
                       final int bufferSize,
                       final ForwardCallback forwardCallback) throws IOException
{
    _inputStream = input.getInputStream();
    _outputStream = output.getOutputStream();
    _forwardCallback = forwardCallback == null ? numberOfBytesForwarded -> {} : forwardCallback;
    _name = "Forwarder-" + input.getLocalSocketAddress() + "->" + output.getRemoteSocketAddress();
    _bufferSize = bufferSize;
}
 
Example 13
/**
 * Returns the server port that accepted the request.
 */
@Override
public InetSocketAddress ipRemote()
{
  Socket s = getSocket();
  
  if (s != null) {
    return (InetSocketAddress) s.getRemoteSocketAddress();
  }
  else {
    return null;
  }
}
 
Example 14
/** Returns the IP address and port of the remote end of the TCP connection, or null if this connection is not connected. */
public InetSocketAddress getRemoteAddressTCP () {
	SocketChannel socketChannel = tcp.socketChannel;
	if (socketChannel != null) {
		Socket socket = tcp.socketChannel.socket();
		if (socket != null) {
			return (InetSocketAddress)socket.getRemoteSocketAddress();
		}
	}
	return null;
}
 
Example 15
Source Project: subethasmtp   File: SMTPServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a SSL socket that wraps the existing socket. This method
 * is called after the client issued the STARTTLS command.
 * <p>
 * Subclasses may override this method to configure the key stores, enabled protocols/
 * cipher suites, enforce client authentication, etc.
 *
 * @param socket the existing socket as created by {@link #createServerSocket()} (not null)
 * @return a SSLSocket
 * @throws IOException when creating the socket failed
 */
public SSLSocket createSSLSocket(Socket socket) throws IOException
{
	SSLSocketFactory sf = ((SSLSocketFactory) SSLSocketFactory.getDefault());
	InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
	SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));

	// we are a server
	s.setUseClientMode(false);

	// allow all supported cipher suites
	s.setEnabledCipherSuites(s.getSupportedCipherSuites());

	return s;
}
 
Example 16
Source Project: xenqtt   File: AbstractMqttChannel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see net.xenqtt.message.MqttChannel#getRemoteAddress()
 */
@Override
public final String getRemoteAddress() {

	if (remoteAddress == null) {
		Socket socket = channel.socket();
		SocketAddress address = socket.isBound() ? socket.getRemoteSocketAddress() : null;
		if (address == null) {
			return "N/A";
		}
		remoteAddress = address.toString();
	}

	return remoteAddress;
}
 
Example 17
public static void wrapXmppTalk(XmppTalk xmppTalk) {
	try {
		ClassLoader classLoader = TlsWrapper.class.getClassLoader();
		InputStream keyInputStream = classLoader.getResourceAsStream("keystore.jks");
		InputStream keyStoreInputStream = classLoader.getResourceAsStream("keystore.jks");
		Socket socket = xmppTalk.getSocket();
		KeyStore ksKeys = KeyStore.getInstance("JKS");
		ksKeys.load(keyInputStream, "123456".toCharArray());
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ksKeys, "123456".toCharArray());
		InputStream keyStoreIS = keyStoreInputStream;
		char[] keyStorePassphrase = "123456".toCharArray();
		ksKeys.load(keyStoreIS, keyStorePassphrase);
		kmf.init(ksKeys, keyStorePassphrase);
		KeyStore ksTrust = KeyStore.getInstance("JKS");
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(ksTrust);
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
		SSLSocketFactory sf = sslContext.getSocketFactory();
		SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
		s.setUseClientMode(false);
		xmppTalk.setSocket(s);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 18
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
  InetSocketAddress socketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
  checkTrusted(chain, socketAddress.getHostName(), socketAddress.getPort());
}
 
Example 19
private String getIdentifer(Socket socket) {
  SocketAddress localSocketAddress = socket.getLocalSocketAddress();
  SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
  return localSocketAddress.toString() + " -> " + remoteSocketAddress.toString();
}
 
Example 20
private static Version readClientVersion(ServerConnection connection)
    throws IOException, VersionException {
  
  Socket socket = connection.getSocket();
  int timeout = connection.getHandShakeTimeout();

  int soTimeout = -1;
  try {
    soTimeout = socket.getSoTimeout();
    socket.setSoTimeout(timeout);
    InputStream is = socket.getInputStream();
    short clientVersionOrdinal = Version.readOrdinalFromInputStream(is);
    if (clientVersionOrdinal == -1) {
      throw new EOFException(
        LocalizedStrings.ServerHandShakeProcessor_HANDSHAKEREADER_EOF_REACHED_BEFORE_CLIENT_VERSION_COULD_BE_READ.toLocalizedString()); 
    }
    Version clientVersion = null;      
    try{
      clientVersion = Version.fromOrdinal(clientVersionOrdinal, true);
    }
    catch (UnsupportedGFXDVersionException uve) {
      // Allows higher version of wan site to connect to server
      if(connection.getCommunicationMode() == Acceptor.GATEWAY_TO_GATEWAY 
          && ! (clientVersionOrdinal == Version.NOT_SUPPORTED_ORDINAL)) {
        return Acceptor.VERSION;
      } else {
        SocketAddress sa = socket.getRemoteSocketAddress();
        String sInfo = "";
        if (sa != null) {
          sInfo = " Client: " + sa.toString() + ".";
        }
        throw new UnsupportedVersionException(uve.getMessage() + sInfo);
      }
    }
  
    if (!clientVersion.compatibleWith(Acceptor.VERSION)) {
      throw new IncompatibleVersionException(clientVersion, Acceptor.VERSION);//we can throw this to restrict
    }                                                 // Backward Compatibilty Support to limited no of versions          
    return clientVersion;                             
  } finally {
    if (soTimeout != -1) {
      try {        
        socket.setSoTimeout(soTimeout);
      }
      catch (IOException ignore) {
      }
    }
  }
}