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

The following examples show how to use java.net.Socket#getRemoteSocketAddress() . 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 check out the related API usage on the sidebar.
Example 1
Source File: SocksSession.java    From sockslib with 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
Source File: BHttpConnectionBase.java    From java-android-websocket-client with Apache License 2.0 6 votes vote down vote up
@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
Source File: TlsWrapper.java    From soapbox-race with GNU General Public License v2.0 5 votes vote down vote up
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 4
Source File: IgniteDiscoveryMassiveNodeFailTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @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 5
Source File: AbstractMqttChannel.java    From xenqtt with 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 6
Source File: SMTPServer.java    From subethasmtp with 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 7
Source File: Connection.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** 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 8
Source File: SocketWrapperBar.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 9
Source File: TCPTunneler.java    From qpid-broker-j with 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 10
Source File: BlurClientManager.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
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 11
Source File: MockTcpTransport.java    From crate with 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 12
Source File: NioSocketSession.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public InetSocketAddress getRemoteAddress() {
    if (channel == null) {
        return null;
    }

    Socket socket = getSocket();

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

    return (InetSocketAddress) socket.getRemoteSocketAddress();
}
 
Example 13
Source File: XEndpoint.java    From redis-rdb-cli with 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 14
Source File: PrivateTlsConfiguration.java    From mireka with 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 15
Source File: BioSocketChannel.java    From canal-1.1.3 with 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 16
Source File: BlobServerConnection.java    From flink with 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 17
Source File: BlobServerConnection.java    From flink with 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 18
Source File: ClientPool.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
private String getIdentifer(Socket socket) {
  SocketAddress localSocketAddress = socket.getLocalSocketAddress();
  SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
  return localSocketAddress.toString() + " -> " + remoteSocketAddress.toString();
}
 
Example 19
Source File: ServerHandShakeProcessor.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
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) {
      }
    }
  }
}
 
Example 20
Source File: ServerFingerprintTrustManager.java    From cava with Apache License 2.0 4 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
  InetSocketAddress socketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
  checkTrusted(chain, socketAddress.getHostName(), socketAddress.getPort());
}