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

The following are Jave code examples for showing how to use getRemoteSocketAddress() 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: java-android-websocket-client   File: BHttpConnectionBase.java   Source Code and License Vote up 6 votes
@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 2
Project: ZooKeeper   File: LearnerHandler.java   Source Code and License Vote up 6 votes
LearnerHandler(Socket sock, BufferedInputStream bufferedInput,
               Leader leader) throws IOException {
    super("LearnerHandler-" + sock.getRemoteSocketAddress());
    this.sock = sock;
    this.leader = leader;
    this.bufferedInput = bufferedInput;
    try {
        leader.self.authServer.authenticate(sock,
                new DataInputStream(bufferedInput));
    } catch (IOException e) {
        LOG.error("Server failed to authenticate quorum learner, addr: {}, closing connection",
                sock.getRemoteSocketAddress(), e);
        try {
            sock.close();
        } catch (IOException ie) {
            LOG.error("Exception while closing socket", ie);
        }
        throw new SaslException("Authentication failure: " + e.getMessage());
    }
}
 
Example 3
Project: lighthouse   File: BHttpConnectionBase.java   Source Code and License Vote up 6 votes
@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 4
Project: HttpInterceptor   File: HttpForwarder.java   Source Code and License Vote up 5 votes
/**
 * Forwarder main loop
 */
@Override
public void run() {
    try {
        // Loop on incoming connections
        while(true) {
            // Accept
            final Socket socket = mServerSocket.accept();
            if(socket == null) break;

            InetSocketAddress localAddr = (InetSocketAddress)socket.getRemoteSocketAddress();
            if(!localAddr.getAddress().isLoopbackAddress())
                continue;

            // Spawn a thread
            Thread t = new Thread() {
                @Override
                public void run() {
                    handle(socket);
                }
            };

            t.start();
        }
    }
    catch(IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: elasticsearch_my   File: MockTcpTransport.java   Source Code and License Vote up 5 votes
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 {
        BytesStreamOutput output = new BytesStreamOutput();
        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 6
Project: neoscada   File: NioSocketSession.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
public InetSocketAddress getRemoteAddress() {
    if (channel == null) {
        return null;
    }

    Socket socket = getSocket();

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

    return (InetSocketAddress) socket.getRemoteSocketAddress();
}
 
Example 7
Project: ZooKeeper   File: SaslQuorumAuthLearner.java   Source Code and License Vote up 5 votes
private void checkAuthStatus(Socket sock, QuorumAuth.Status qpStatus)
        throws SaslException {
    if (qpStatus == QuorumAuth.Status.SUCCESS) {
        LOG.info("Successfully completed the authentication using SASL. server addr: {}, status: {}",
                sock.getRemoteSocketAddress(), qpStatus);
    } else {
        throw new SaslException("Authentication failed against server addr: "
                        + sock.getRemoteSocketAddress() + ", qpStatus: "
                        + qpStatus);
    }
}
 
Example 8
Project: buabook-common   File: DataSocket.java   Source Code and License Vote up 5 votes
/**
 * Instantiates the wrapper object based on an existing {@link Socket}
 * @throws DataSocketFailedToInitialiseException If the socket provided is <code>null</code> or if there 
 * is any error when attempting to create the {@link DataInputStream} or {@link DataOutputStream}.
 * @see #initialiseIOStreams()
 */
public DataSocket(Socket socket) throws DataSocketFailedToInitialiseException {
	if(socket == null)
		throw new DataSocketFailedToInitialiseException(new NullPointerException("socket"));
	
	this.socket = socket;
	this.remoteSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

	initialiseIOStreams();
	
	log.info("New connection on socket: {}", remoteSocketAddress);
}
 
Example 9
Project: soapbox-race-core   File: TlsWrapper.java   Source Code and License Vote up 5 votes
public static void wrapXmppTalk(OpenFireTalk xmppTalk) {
	try {
		Socket socket = xmppTalk.getSocket();
		SSLContext sslContext = getSslContext();
		InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
		SSLSocketFactory sf = sslContext.getSocketFactory();
		SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));
		s.setUseClientMode(true);
		s.startHandshake();
		xmppTalk.setSocket(s);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 10
Project: fuck_zookeeper   File: LearnerHandler.java   Source Code and License Vote up 4 votes
LearnerHandler(Socket sock, Leader leader) throws IOException {
    super("LearnerHandler-" + sock.getRemoteSocketAddress());
    this.sock = sock;
    this.leader = leader;
    leader.addLearnerHandler(this);
}
 
Example 11
Project: https-github.com-apache-zookeeper   File: ClientCnxnSocketNIO.java   Source Code and License Vote up 4 votes
private void updateSocketAddresses() {
    Socket socket = ((SocketChannel) sockKey.channel()).socket();
    localSocketAddress = socket.getLocalSocketAddress();
    remoteSocketAddress = socket.getRemoteSocketAddress();
}
 
Example 12
Project: https-github.com-apache-zookeeper   File: LearnerHandler.java   Source Code and License Vote up 4 votes
LearnerHandler(Socket sock, Leader leader) throws IOException {
    super("LearnerHandler-" + sock.getRemoteSocketAddress());
    this.sock = sock;
    this.leader = leader;
    leader.addLearnerHandler(this);
}
 
Example 13
Project: monarch   File: ServerHandShakeProcessor.java   Source Code and License Vote up 4 votes
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 (UnsupportedVersionException 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 14
Project: openjdk-jdk10   File: ExtensionsWithLDAP.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {
    String extension = args[0];
    String targetHost = args[1];

    // enable CRLDP and AIA extensions
    System.setProperty("com.sun.security.enableCRLDP", "true");
    System.setProperty("com.sun.security.enableAIAcaIssuers", "true");

    Path hostsFilePath = Paths.get(System.getProperty("test.src", ".")
            + File.separator + extension);
    System.setProperty("jdk.net.hosts.file",
            hostsFilePath.toFile().getAbsolutePath());

    X509Certificate trustedCert = loadCertificate(CA_CERT);
    X509Certificate eeCert = loadCertificate(EE_CERT);

    Set<TrustAnchor> trustedCertsSet = new HashSet<>();
    trustedCertsSet.add(new TrustAnchor(trustedCert, null));

    CertPath cp = (CertPath) CertificateFactory.getInstance("X509")
            .generateCertPath(Arrays.asList(eeCert));

    // CertPath validator should try to parse CRLDP and AIA extensions,
    // and load CRLs/certs which they point to.
    // If proxy server catches requests for resolving host names
    // which extensions contain, then it means that CertPath validator
    // tried to load CRLs/certs which they point to.
    List<String> hosts = new ArrayList<>();
    Consumer<Socket> socketConsumer = (Socket socket) -> {
        InetSocketAddress remoteAddress
                = (InetSocketAddress) socket.getRemoteSocketAddress();
        hosts.add(remoteAddress.getHostName());
    };
    try (SocksProxy proxy = SocksProxy.startProxy(socketConsumer)) {
        CertPathValidator.getInstance("PKIX").validate(cp,
                new PKIXParameters(trustedCertsSet));
        throw new RuntimeException("CertPathValidatorException not thrown");
    } catch (CertPathValidatorException cpve) {
        System.out.println("Expected exception: " + cpve);
    }

    if (!hosts.contains(targetHost)) {
        throw new RuntimeException(
                String.format("The %s from %s extension is not requested",
                        targetHost, extension));
    }

    System.out.println("Test passed");
}
 
Example 15
Project: BiglyBT   File: SocketServer.java   Source Code and License Vote up 4 votes
/**
 * start up the server socket and when a new connection is received, check that
 * the source address is in our permitted list and if so, start a new console input
 * on that socket.
 */
@Override
public void run()
{
	int threadNum = 1;
	System.out.println("Telnet server started. Listening on port: " + serverSocket.getLocalPort());

	while( true ) {
		try {
			Socket socket = serverSocket.accept();

			InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();

			if( addr.isUnresolved() || ! isAllowed(addr) ) {
				System.out.println("TelnetUI: rejecting connection from: " + addr + " as address is not allowed");
				socket.close();
			}
			else {
				System.out.println("TelnetUI: accepting connection from: " + addr);
				int loginAttempts = 0;

				while( true ) {
					// TODO: might want to put this in another thread so the port doesnt block while the user logs in

					//System.out.println("TelnetUI: starting login" );

					UserProfile profile = login( socket.getInputStream(), socket.getOutputStream() );

					//System.out.println("TelnetUI: login profile obtained" );

					if( profile != null ) {

						//System.out.println("TelnetUI: creating console input" );

						ui.createNewConsoleInput("Telnet Console " + threadNum++, socket.getInputStream(), new PrintStream(socket.getOutputStream()), profile);
						break;
					}

					//System.out.println("TelnetUI: failed to obtain login profile" );

					loginAttempts++;

					if( loginAttempts >= maxLoginAttempts ) {
						System.out.println("TelnetUI: rejecting connection from: " + addr + " as number of failed connections > max login attempts (" + maxLoginAttempts + ")");
						socket.close();
						break;
					}
				}
			}
		}
		catch (Throwable t) {
			t.printStackTrace();
			break;
		}
	}
}
 
Example 16
Project: ZooKeeper   File: QuorumCnxManager.java   Source Code and License Vote up 4 votes
QuorumConnectionReceiverThread(final Socket sock) {
    super("QuorumConnectionReceiverThread-" + sock.getRemoteSocketAddress());
    this.sock = sock;
}
 
Example 17
Project: ZooKeeper   File: SaslQuorumAuthLearner.java   Source Code and License Vote up 4 votes
@Override
public void authenticate(Socket sock, String hostName) throws IOException {
    if (!quorumRequireSasl) { // let it through, we don't require auth
        LOG.info("Skipping SASL authentication as {}={}",
                QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED,
                quorumRequireSasl);
        return;
    }
    SaslClient sc = null;
    String principalConfig = SecurityUtils
            .getServerPrincipal(quorumServicePrincipal, hostName);
    try {
        DataOutputStream dout = new DataOutputStream(
                sock.getOutputStream());
        DataInputStream din = new DataInputStream(sock.getInputStream());
        byte[] responseToken = new byte[0];
        sc = SecurityUtils.createSaslClient(learnerLogin.getSubject(),
                principalConfig,
                QuorumAuth.QUORUM_SERVER_PROTOCOL_NAME,
                QuorumAuth.QUORUM_SERVER_SASL_DIGEST, LOG, "QuorumLearner");

        if (sc.hasInitialResponse()) {
            responseToken = createSaslToken(new byte[0], sc, learnerLogin);
        }
        send(dout, responseToken);
        QuorumAuthPacket authPacket = receive(din);
        QuorumAuth.Status qpStatus = QuorumAuth.Status
                .getStatus(authPacket.getStatus());
        while (!sc.isComplete()) {
            switch (qpStatus) {
            case SUCCESS:
                responseToken = createSaslToken(authPacket.getToken(), sc,
                        learnerLogin);
                // we're done; don't expect to send another BIND
                if (responseToken != null) {
                    throw new SaslException(
                            "Protocol error: attempting to send response after completion"
                                    + ". Server addr: "
                                    + sock.getRemoteSocketAddress());
                }
                break;
            case IN_PROGRESS:
                responseToken = createSaslToken(authPacket.getToken(), sc,
                        learnerLogin);
                send(dout, responseToken);
                authPacket = receive(din);
                qpStatus = QuorumAuth.Status
                        .getStatus(authPacket.getStatus());
                break;
            case ERROR:
                throw new SaslException(
                        "Authentication failed against server addr: "
                                + sock.getRemoteSocketAddress());
            default:
                LOG.warn("Unknown status:{}!", qpStatus);
                throw new SaslException(
                        "Authentication failed against server addr: "
                                + sock.getRemoteSocketAddress());
            }
        }

        // Validate status code at the end of authentication exchange.
        checkAuthStatus(sock, qpStatus);
    } finally {
        if (sc != null) {
            try {
                sc.dispose();
            } catch (SaslException e) {
                LOG.error("SaslClient dispose() failed", e);
            }
        }
    }
    return;
}