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

The following examples show how to use java.net.Socket#getInetAddress() . 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: RubySSLSocketFactory.java    From PixivforMuzei3 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException
{
    InetAddress address = plainSocket.getInetAddress();
    Log.i("!", "Address: " + address.getHostAddress());
    if (autoClose)
    {
        plainSocket.close();
    }
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();
    Log.i("!", "Protocol " + session.getProtocol() + " PeerHost " + session.getPeerHost() +
            " CipherSuite " + session.getCipherSuite());
    return ssl;
}
 
Example 2
Source File: FreeColServer.java    From freecol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 FreeColException on extreme confusion.
 * @exception IOException if the socket was already broken.
 * @exception XMLStreamException on stream problem.
 */
public void addNewUserConnection(Socket socket)
    throws FreeColException, IOException, XMLStreamException {
    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
    c.startReceiving();
    //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 3
Source File: ConnectionData.java    From remotekeyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a ConnectionData instance storing vital
 * information about a connection.
 *
 * @param sock Socket of the inbound connection.
 */
public ConnectionData(Socket sock, ConnectionManager cm) {
  m_Socket = sock;
  m_CM = cm;
  m_IP = sock.getInetAddress();
  setHostName();
  setHostAddress();
  setLocale();
  m_Port = sock.getPort();
  //this will set a default geometry and terminal type for the terminal
  m_TerminalGeometry = new int[2];
  m_TerminalGeometry[0] = 80;	//width
  m_TerminalGeometry[1] = 25;	//height
  m_NegotiatedTerminalType = "default";
  m_Environment = new HashMap(20);
  //this will stamp the first activity for validity :)
  activity();
}
 
Example 4
Source File: XmppConnection.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
    final TlsFactoryVerifier tlsFactoryVerifier;
    try {
        tlsFactoryVerifier = getTlsFactoryVerifier();
    } catch (final NoSuchAlgorithmException | KeyManagementException e) {
        throw new StateChangingException(Account.State.TLS_ERROR);
    }
    final InetAddress address = socket.getInetAddress();
    final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
    SSLSocketHelper.setSecurity(sslSocket);
    SSLSocketHelper.setHostname(sslSocket, account.getServer());
    SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
    if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
        FileBackend.close(sslSocket);
        throw new StateChangingException(Account.State.TLS_ERROR);
    }
    return sslSocket;
}
 
Example 5
Source File: Selector.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Generate the description for a SocketChannel
 */
private String socketDescription(SocketChannel channel) {
  Socket socket = channel.socket();
  if (socket == null) {
    return "[unconnected socket]";
  } else if (socket.getInetAddress() != null) {
    return socket.getInetAddress().toString();
  } else {
    return socket.getLocalAddress().toString();
  }
}
 
Example 6
Source File: SocketServer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
 static
 void main(String argv[]) {
   if(argv.length == 3)
     init(argv[0], argv[1], argv[2]);
   else
     usage("Wrong number of arguments.");

   try {
     cat.info("Listening on port " + port);
     ServerSocket serverSocket = new ServerSocket(port);
     while(true) {
cat.info("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
InetAddress inetAddress =  socket.getInetAddress();
cat.info("Connected to client at " + inetAddress);

LoggerRepository h = (LoggerRepository) server.hierarchyMap.get(inetAddress);
if(h == null) {
  h = server.configureHierarchy(inetAddress);
}

cat.info("Starting new socket node.");
new Thread(new SocketNode(socket, h)).start();
     }
   }
   catch(Exception e) {
     e.printStackTrace();
   }
 }
 
Example 7
Source File: MMOConnection.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
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
Source File: ConnectionImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public InetAddress getPeerAddress() {
    synchronized (lock) {
        final Socket socket = this.socket;
        if (socket != null) {
            return socket.getInetAddress();
        } else {
            return null;
        }
    }
}
 
Example 9
Source File: SmtpConnection.java    From greenmail with Apache License 2.0 5 votes vote down vote up
public SmtpConnection(SmtpHandler handler, Socket sock)
        throws IOException {
    this.sock = sock;
    clientAddress = sock.getInetAddress();
    OutputStream o = sock.getOutputStream();
    InputStream i = sock.getInputStream();
    out = InternetPrintWriter.createForEncoding(o, true, EncodingUtil.CHARSET_EIGHT_BIT_ENCODING);
    in = new BufferedReader(new InputStreamReader(i, StandardCharsets.US_ASCII));

    this.handler = handler;
}
 
Example 10
Source File: SessionThread.java    From mireka with Apache License 2.0 5 votes vote down vote up
public SessionThread(PopServer server, ServerThread serverThread,
        Socket socket) throws IOException {
    super(SessionThread.class.getName() + "-" + socket.getInetAddress()
            + ":" + socket.getPort());
    this.serverThread = serverThread;
    setSocket(socket);
    session = new Session(server, this);
    this.commandHandler = new CommandHandler(session);
}
 
Example 11
Source File: RubySSLSocketFactory.java    From Pixiv-Shaft with MIT License 5 votes vote down vote up
@NotNull
public Socket createSocket(@Nullable Socket paramSocket, @Nullable String paramString, int paramInt, boolean paramBoolean) throws IOException {
    if (paramSocket == null)
        Intrinsics.throwNpe();
    InetAddress inetAddress = paramSocket.getInetAddress();
    Intrinsics.checkExpressionValueIsNotNull(inetAddress, "address");
    Log.d("address", inetAddress.getHostAddress());
    if (paramBoolean)
        paramSocket.close();
    SocketFactory socketFactory = SSLCertificateSocketFactory.getDefault(0);
    if (socketFactory != null) {
        Socket socket = socketFactory.createSocket(inetAddress, paramInt);
        if (socket != null) {
            ((SSLSocket) socket).setEnabledProtocols(((SSLSocket) socket).getSupportedProtocols());
            Log.i("X", "Setting SNI hostname");
            SSLSession sSLSession = ((SSLSocket) socket).getSession();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Established ");
            Intrinsics.checkExpressionValueIsNotNull(sSLSession, "session");
            stringBuilder.append(sSLSession.getProtocol());
            stringBuilder.append(" connection with ");
            stringBuilder.append(sSLSession.getPeerHost());
            stringBuilder.append(" using ");
            stringBuilder.append(sSLSession.getCipherSuite());
            Log.d("X", stringBuilder.toString());
            return socket;
        }
        throw new TypeCastException("null cannot be cast to non-null type javax.net.ssl.SSLSocket");
    }
    throw new TypeCastException("null cannot be cast to non-null type android.net.SSLCertificateSocketFactory");
}
 
Example 12
Source File: NioSession.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public InetSocketAddress getRemoteAddress() {
	Socket socket = getSocket();
	SocketAddress sa = socket.getRemoteSocketAddress();
	if (sa instanceof InetSocketAddress)
		return (InetSocketAddress)sa;
	InetAddress ia = socket.getInetAddress();
	return ia != null ? new InetSocketAddress(ia, socket.getPort()) : null;
}
 
Example 13
Source File: ModbusSlaveConnectionTCP.java    From jlibmodbus with Apache License 2.0 5 votes vote down vote up
ModbusSlaveConnectionTCP(Socket socket) throws ModbusIOException {
    try {
        this.socket = socket;
        transport = ModbusTransportFactory.createTCP(socket);
        clientInfo = new TcpClientInfo(new TcpParameters(socket.getInetAddress(), socket.getPort(), socket.getKeepAlive()), false);

        open();
    } catch (Exception e) {
        throw new ModbusIOException(e);
    }
}
 
Example 14
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getRemoteAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getInetAddress();
   int port = s.getPort();
   return new InetSocketAddress(ia, port);
}
 
Example 15
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getRemoteAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getInetAddress();
   int port = s.getPort();
   return new InetSocketAddress(ia, port);
}
 
Example 16
Source File: Client.java    From anthelion with Apache License 2.0 4 votes vote down vote up
protected Socket __openPassiveDataConnection(int command, String arg)
      throws IOException, FtpExceptionCanNotHaveDataConnection {
        Socket socket;

//        // 20040317, xing, accommodate ill-behaved servers, see below
//        int port_previous = __passivePort;

        if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
          throw new FtpExceptionCanNotHaveDataConnection(
            "pasv() failed. " + getReplyString());

        try {
          __parsePassiveModeReply(getReplyStrings()[0]);
        } catch (MalformedServerReplyException e) {
          throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
        }

//        // 20040317, xing, accommodate ill-behaved servers, see above
//        int count = 0;
//        System.err.println("__passivePort "+__passivePort);
//        System.err.println("port_previous "+port_previous);
//        while (__passivePort == port_previous) {
//          // just quit if too many tries. make it an exception here?
//          if (count++ > 10)
//            return null;
//          // slow down further for each new try
//          Thread.sleep(500*count);
//          if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
//            throw new FtpExceptionCanNotHaveDataConnection(
//              "pasv() failed. " + getReplyString());
//            //return null;
//          try {
//            __parsePassiveModeReply(getReplyStrings()[0]);
//          } catch (MalformedServerReplyException e) {
//            throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
//          }
//        }

        socket = _socketFactory_.createSocket(__passiveHost, __passivePort);

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
          socket.close();
          return null;
        }

        if (__remoteVerificationEnabled && !verifyRemote(socket))
        {
            InetAddress host1, host2;

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

            socket.close();

            // our precaution
            throw new FtpExceptionCanNotHaveDataConnection(
                "Host attempting data connection " + host1.getHostAddress() +
                " is not same as server " + host2.getHostAddress() +
                " So we intentionally close it for security precaution."
                );
        }

        if (__dataTimeout >= 0)
            socket.setSoTimeout(__dataTimeout);

        return socket;
    }
 
Example 17
Source File: Client.java    From nutch-htmlunit with Apache License 2.0 4 votes vote down vote up
/** 
     * open a passive data connection socket
     * @param command
     * @param arg
     * @return
     * @throws IOException
     * @throws FtpExceptionCanNotHaveDataConnection
     */
    protected Socket __openPassiveDataConnection(int command, String arg)
      throws IOException, FtpExceptionCanNotHaveDataConnection {
        Socket socket;

//        // 20040317, xing, accommodate ill-behaved servers, see below
//        int port_previous = __passivePort;

        if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
          throw new FtpExceptionCanNotHaveDataConnection(
            "pasv() failed. " + getReplyString());

        try {
          __parsePassiveModeReply(getReplyStrings()[0]);
        } catch (MalformedServerReplyException e) {
          throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
        }

//        // 20040317, xing, accommodate ill-behaved servers, see above
//        int count = 0;
//        System.err.println("__passivePort "+__passivePort);
//        System.err.println("port_previous "+port_previous);
//        while (__passivePort == port_previous) {
//          // just quit if too many tries. make it an exception here?
//          if (count++ > 10)
//            return null;
//          // slow down further for each new try
//          Thread.sleep(500*count);
//          if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
//            throw new FtpExceptionCanNotHaveDataConnection(
//              "pasv() failed. " + getReplyString());
//            //return null;
//          try {
//            __parsePassiveModeReply(getReplyStrings()[0]);
//          } catch (MalformedServerReplyException e) {
//            throw new FtpExceptionCanNotHaveDataConnection(e.getMessage());
//          }
//        }

        socket = _socketFactory_.createSocket(__passiveHost, __passivePort);

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
          socket.close();
          return null;
        }

        if (__remoteVerificationEnabled && !verifyRemote(socket))
        {
            InetAddress host1, host2;

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

            socket.close();

            // our precaution
            throw new FtpExceptionCanNotHaveDataConnection(
                "Host attempting data connection " + host1.getHostAddress() +
                " is not same as server " + host2.getHostAddress() +
                " So we intentionally close it for security precaution."
                );
        }

        if (__dataTimeout >= 0)
            socket.setSoTimeout(__dataTimeout);

        return socket;
    }
 
Example 18
Source File: WebTlsSniSocketFactory.java    From YCWebView with Apache License 2.0 4 votes vote down vote up
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose)
        throws IOException {
    String peerHost = this.conn.getRequestProperty("Host");
    if (peerHost == null){
        peerHost = host;
    }
    X5LogUtils.i("customized createSocket. host: " + peerHost);
    InetAddress address = plainSocket.getInetAddress();
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();
    }
    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory)
            SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);

    // enable TLSv1.1/1.2 if available
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());

    // set up SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        X5LogUtils.i("Setting SNI hostname");
        sslSocketFactory.setHostname(ssl, peerHost);
    } else {
        X5LogUtils.d("No documented SNI support on Android <4.2, trying with reflection");
        try {
            java.lang.reflect.Method setHostnameMethod =
                    ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, peerHost);
        } catch (Exception e) {
            X5LogUtils.e("SNI not useable", e);
        }
    }
    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(peerHost, session)){
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);
    }
    X5LogUtils.i("Established " + session.getProtocol() + " connection with " +
            session.getPeerHost() + " using " + session.getCipherSuite());
    return ssl;
}
 
Example 19
Source File: RMBTTest.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
protected Socket connect(final TestResult testResult) throws IOException
{
    log(String.format(Locale.US, "thread %d: connecting...", threadId));
    
    final InetAddress inetAddress = InetAddress.getByName(params.getHost());
    
    System.out.println("connecting to: " + inetAddress.getHostName() + ":" + params.getPort());
    final Socket s = getSocket(inetAddress.getHostAddress(), params.getPort(), true, 20000);
    
    testResult.ip_local = s.getLocalAddress();
    testResult.ip_server = s.getInetAddress();
    
    testResult.port_remote = s.getPort();
    
    if (s instanceof SSLSocket)
    {
        final SSLSocket sslSocket = (SSLSocket) s;
        final SSLSession session = sslSocket.getSession();
        testResult.encryption = String.format(Locale.US, "%s (%s)", session.getProtocol(), session.getCipherSuite());
    }
    
    log(String.format(Locale.US, "thread %d: ReceiveBufferSize: '%s'.", threadId, s.getReceiveBufferSize()));
    log(String.format(Locale.US, "thread %d: SendBufferSize: '%s'.", threadId, s.getSendBufferSize()));
    
    if (in != null)
        totalDown += in.getCount();
    if (out != null)
        totalUp += out.getCount();
    
    in = new InputStreamCounter(s.getInputStream());
    reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"), 4096);
    out = new OutputStreamCounter(s.getOutputStream());
    
    String line = reader.readLine();
    if (!line.equals(EXPECT_GREETING))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected '%s'", threadId, line, EXPECT_GREETING));
        return null;
    }
    
    line = reader.readLine();
    if (!line.startsWith("ACCEPT "))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected 'ACCEPT'", threadId, line));
        return null;
    }
    
    final String send = String.format(Locale.US, "TOKEN %s\n", params.getToken());
    
    out.write(send.getBytes("US-ASCII"));
    
    line = reader.readLine();
    
    if (line == null)
    {
        log(String.format(Locale.US, "thread %d: got no answer expected 'OK'", threadId, line));
        return null;
    }
    else if (!line.equals("OK"))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected 'OK'", threadId, line));
        return null;
    }
    
    line = reader.readLine();
    final Scanner scanner = new Scanner(line);
    try
    {
        if (!"CHUNKSIZE".equals(scanner.next()))
        {
            log(String.format(Locale.US, "thread %d: got '%s' expected 'CHUNKSIZE'", threadId, line));
            return null;
        }
        try
        {
            chunksize = scanner.nextInt();
            log(String.format(Locale.US, "thread %d: CHUNKSIZE is %d", threadId, chunksize));
        }
        catch (final Exception e)
        {
            log(String.format(Locale.US, "thread %d: invalid CHUNKSIZE: '%s'", threadId, line));
            return null;
        }
        if (buf == null || buf != null && buf.length != chunksize)
            buf = new byte[chunksize];
        return s;
    }
    finally
    {
        scanner.close();
    }
}
 
Example 20
Source File: HandShake.java    From gemfirexd-oss with Apache License 2.0 2 votes vote down vote up
/**
 * Return fake, temporary DistributedMember to represent the other vm this 
 * vm is connecting to
 * 
 * @param sock the socket this handshake is operating on
 * @return temporary id to reprent the other vm
 */
private DistributedMember getDistributedMember(Socket sock) {
  return new InternalDistributedMember(
      sock.getInetAddress(), sock.getPort(), false);
}