Example usage for java.net Socket getInetAddress

List of usage examples for java.net Socket getInetAddress

Introduction

In this page you can find the example usage for java.net Socket getInetAddress.

Prototype

public InetAddress getInetAddress() 

Source Link

Document

Returns the address to which the socket is connected.

Usage

From source file:org.apache.jmeter.protocol.amf.proxy.AmfProxy.java

/**
 * Negotiate a SSL connection.// w w  w.  j a v  a 2 s  . co m
 *
 * @param sock socket in
 * @param host
 * @return a new client socket over ssl
 * @throws Exception if negotiation failed
 */
private Socket startSSL(Socket sock, String host) throws IOException {
    SSLSocketFactory sslFactory = getSSLSocketFactory(host);
    SSLSocket secureSocket;
    if (sslFactory != null) {
        try {
            secureSocket = (SSLSocket) sslFactory.createSocket(sock, sock.getInetAddress().getHostName(),
                    sock.getPort(), true);
            secureSocket.setUseClientMode(false);
            if (log.isDebugEnabled()) {
                log.debug("SSL transaction ok with cipher: " + secureSocket.getSession().getCipherSuite());
            }
            return secureSocket;
        } catch (IOException e) {
            log.error("Error in SSL socket negotiation: ", e);
            throw e;
        }
    } else {
        log.warn("Unable to negotiate SSL transaction, no keystore?");
        throw new IOException("Unable to negotiate SSL transaction, no keystore?");
    }
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;

    try {//from  w  ww  .j  av a2  s.  c om
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

From source file:com.atomicleopard.thundr.ftp.commons.SocketClient.java

/**
 * 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>/*from   w ww .java 2s .c  om*/
 * @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);
}

From source file:gov.hhs.fha.nhinc.lift.proxy.properties.imp.ProducerProxyPropertiesService.java

@Override
public Socket getSocketToServerForRequest(LiftConnectionRequestToken request) throws IOException {

    Socket socket = new Socket();
    try {// w  w w.  jav a2  s.  c o m
        String fileServerIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_FILESERVER_IP);
        String fileServerPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_FILESERVER_PORT);
        int portNum = Integer.parseInt(fileServerPort);

        SocketAddress socketAddr = new InetSocketAddress(fileServerIP, portNum);
        socket.connect(socketAddr);

    } catch (PropertyAccessException ex) {
        log.error(ex.getMessage());
    }
    log.debug("Creating socket " + socket.getInetAddress() + ": " + socket.getPort());
    return socket;
}

From source file:Proxy.java

String toString(SocketChannel ch) {
    StringBuilder sb = new StringBuilder();
    Socket sock;

    if (ch == null)
        return null;
    if ((sock = ch.socket()) == null)
        return null;
    sb.append(sock.getInetAddress().getHostName()).append(':').append(sock.getPort());
    return sb.toString();
}

From source file:cloud.elasticity.elastman.Sensor.java

public synchronized void addClient(Socket cs) {
    try {// ww  w  . j  a  v  a2s.  c  o m
        cs.setSoTimeout(40000); // wait max 40 seconds;
    } catch (SocketException e) {
        log.error("Error: Can't set socket time out!");
        log.error(e.getMessage());
    }
    clientSockets.add(new MyIO(cs));
    log.info("Client added: {}", cs.getInetAddress());
}

From source file:com.kyne.webby.rtk.web.Connection.java

@SuppressWarnings("unchecked")
private void handleRequest(final String url, final String params, final Socket clientSocket)
        throws IOException, ClassNotFoundException {
    try {/*from w  ww . j  a v a  2  s. co  m*/
        LogHelper.debug("Processing new request : " + url + " with params : " + params + ". ClientSocket = "
                + clientSocket);
        // Clean too old authentications
        this.cleanOldAuthentications();
        // If still connected, update
        this.updateLastAction(clientSocket.getInetAddress());

        // Favicons
        if (url.startsWith("/favicon.ico")) {
            return; // Ignore
        }
        // JS, CSS and images
        else if (url.startsWith("/js/")) {
            this.webServer.printStaticFile(this.htmlDir() + url, "text/javascript", clientSocket, null);
            return;
        } else if (url.startsWith("/css/")) {
            this.webServer.printStaticFile(this.htmlDir() + url, "text/css", clientSocket, null);
            return;
        } else if (url.startsWith("/images/")) {
            if (url.endsWith("png")) {
                this.webServer.printStaticFile(this.htmlDir() + url, "images/png", clientSocket, null);
            } else if (url.endsWith("gif")) {
                this.webServer.printStaticFile(this.htmlDir() + url, "images/gif", clientSocket, null);
            }
            return;
        }
        // Unrestricted HTML Pages
        if ("/login".equals(url)) { // Login form
            final String login = this.getParam("login", params);
            final String pass = this.getParam("password", params);
            if (login == null && pass == null) { // Show form
                this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                        this.asMap("errorMsg:none"));
                return;
            } else {
                // Try to authenticate...
                if (this.checkAuthentication(login, pass)) {
                    this.logUser(clientSocket.getInetAddress());
                    final Map<InetAddress, String> lastUrlByIp = this.webServer.getLastUrlByIp();
                    final String redirectUrl = lastUrlByIp.get(clientSocket.getInetAddress());
                    this.webServer.clearLastUrlFor(clientSocket.getInetAddress());
                    final String finalUrl = redirectUrl == null ? "/index" : redirectUrl;
                    LogHelper.info("Login successful. Redirect to " + finalUrl);
                    this.handleRequest(finalUrl, params, clientSocket);
                    return;
                } else {
                    LogHelper.info("Wrong login / password");
                    this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                            this.asMap("errorMsg:Wrong Login/Password"));
                    return;
                }
            }
        } else if ("/logout".equals(url)) {
            this.logOut(clientSocket.getInetAddress().getHostAddress());
            this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket, null);
            return;
        } else if ("/404".equals(url)) {
            this.webServer.printStaticFile(this.htmlDir() + "404.html", "text/html", clientSocket, null);
            return;
        }
        //'Contextual calls'
        else if (isContextualCallUrl(url)) {
            LogHelper.info("Contextual call detected : " + url);
            final String login = getParam("login", params);
            final String password = getParam("password", params);
            boolean authenticated = this.checkAuthentication(login, password);
            if (!authenticated) {
                LogHelper.info("Wrong login / password");
                this.webServer.printStaticFile(this.htmlDir() + "login.html", "text/html", clientSocket,
                        this.asMap("errorMsg:Wrong Login/Password"));
                return;
            } else {
                // Handle the contextual call
                if (url.equals("/backupRemote")) {
                    this.rtkModule.backupServer(false, webServer.getDefaultWorldName());
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                }
            }
        }
        // Restricted HTML Pages
        else if (this.isRestrictedUrl(url)) {
            if (this.isUserLoggedIn(clientSocket.getInetAddress())) {
                // User may access any pages
                if ("/".equals(url) || "/index".equals(url)) { // Index
                    this.webServer.printStaticFile(this.htmlDir() + "index.html", "text/html", clientSocket,
                            this.asMap("errorMsg:none;infoMsg:none;warningMsg:none"));
                    return;
                } else if ("/indexJSON".equals(url)) {
                    this.webServer.handleIndexJSON(clientSocket);
                    return;
                } else if ("/execCommand".equals(url)) {
                    final String command = this.getParam("command", params);
                    this.rtkModule.handleCommand(command);
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/execBukkitCommand".equals(url)) {
                    final String command = this.getParam("command", params);
                    this.rtkModule.handleBukkitCommand(command);
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/backupServer".equals(url)) {
                    this.rtkModule.backupServer(false, webServer.getDefaultWorldName());
                    this.webServer.printJSONObject(new JSONObject(), clientSocket);
                    return;
                } else if ("/backups".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "backups.html", "text/html", clientSocket,
                            null);
                    return;
                } else if ("/backupsJSON".equals(url)) {
                    final JSONObject backupJSON = this.webServer.getBackupJSON();
                    this.webServer.printJSONObject(backupJSON, clientSocket);
                    return;
                } else if ("/deleteBackup".equals(url)) {
                    final String fileName = this.getParam("fileName", params);
                    final boolean success = this.webServer.deleteBackup(fileName);
                    final JSONObject response = new JSONObject();
                    response.put("success", success);
                    this.webServer.printJSONObject(response, clientSocket);
                    return;
                } else if ("/restoreBackup".equals(url)) {
                    // First, backup the server
                    this.rtkModule.backupServer(true, webServer.getDefaultWorldName());

                    // Then, shutdown the server
                    this.rtkModule.handleCommand(ToolkitAction.HOLD.name());
                    this.checkForShutdown();

                    // Restore backup
                    final String fileName = this.getParam("fileName", params);
                    boolean success = this.rtkModule.restoreBackup(fileName);
                    JSONObject response = new JSONObject();
                    response.put("success", success);

                    //Restart
                    this.rtkModule.handleCommand(ToolkitAction.UNHOLD.name());
                    this.webServer.printJSONObject(response, clientSocket);
                    return;
                } else if ("/about".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "about.html", "text/html", clientSocket,
                            this.asMap("version:" + WebbyKeys.VERSION));
                    return;
                } else if ("/license".equals(url)) {
                    final String license = this.webServer.getLicenseTxt();
                    this.webServer.printPlainText(license, clientSocket);
                    return;
                } else if ("/bukkitconf".equals(url)) {
                    this.webServer.printStaticFile(this.htmlDir() + "bukkitconf.html", "text/html",
                            clientSocket, null);
                    return;
                } else if ("/saveConf".equals(url)) {
                    this.webServer.saveBukkitConf(getParam("dataConf", params));
                    this.webServer.printJSON(new JSONObject(), clientSocket);
                    return;
                } else if ("/bukkitconfJSON".equals(url)) {
                    final Map<String, Object> conJSON = this.webServer.getConfJSON();
                    this.webServer.printJSON(conJSON, clientSocket);
                    return;
                }
            } else {
                this.webServer.saveLastUrlFor(clientSocket.getInetAddress(), url);
                this.handleRequest("/login", params, clientSocket); // Redirect to login
                return;
            }
        }
        // Not found -> wrong url
        LogHelper.warn("Unknow/Unsupported URL requested : " + url + ". Params = " + params);
        this.handleRequest("/404", params, clientSocket); //Forward to 404
    } catch (final SocketException e) {
        /* Go to hell */ } catch (final Exception e) {
        LogHelper.error("An error occured while processing a new HTTP request", e);
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient.java

/**
 * Sends client SASL negotiation for a newly allocated socket if required.
 *
 * @param socket connection socket//  ww w.  ja v  a  2 s . c  o  m
 * @param underlyingOut connection output stream
 * @param underlyingIn connection input stream
 * @param encryptionKeyFactory for creation of an encryption key
 * @param accessToken connection block access token
 * @param datanodeId ID of destination DataNode
 * @return new pair of streams, wrapped after SASL negotiation
 * @throws IOException for any error
 */
public IOStreamPair newSocketSend(Socket socket, OutputStream underlyingOut, InputStream underlyingIn,
        DataEncryptionKeyFactory encryptionKeyFactory, Token<BlockTokenIdentifier> accessToken,
        DatanodeID datanodeId) throws IOException {
    // The encryption key factory only returns a key if encryption is enabled.
    DataEncryptionKey encryptionKey = !trustedChannelResolver.isTrusted()
            ? encryptionKeyFactory.newDataEncryptionKey()
            : null;
    IOStreamPair ios = send(socket.getInetAddress(), underlyingOut, underlyingIn, encryptionKey, accessToken,
            datanodeId);
    return ios != null ? ios : new IOStreamPair(underlyingIn, underlyingOut);
}

From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

public void run() {
    ServerSocket serverSocket = null;
    Socket connectionSocket = null;
    try {/*from w w w.ja va 2s . c om*/
        log.info("Trying to bind to localhost on port " + Integer.toString(port) + "...");
        serverSocket = new ServerSocket(port);
        log.info("Running Simple WebServer!\n");
        connectionSocket = serverSocket.accept();
        connectionSocket.setSoTimeout(30000);
        //go in a infinite loop, wait for connections, process request, send response
        while (running) {
            log.info("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                BufferedReader input;
                if (!connectionSocket.isClosed()) {
                    InetAddress client = connectionSocket.getInetAddress();
                    log.info(client.getHostName() + " connected to server.\n");
                    input = new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset()));
                    if (input.ready()) {
                        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
                        httpHandler(input, output);
                    }
                }
                //Prepare a outputStream. This will be used sending back our response
                //(header + requested file) to the client.
            } catch (Exception e) { //catch any errors, and print them
                log.info("\nError:" + e.getMessage());
                running = false;
            }
        }
    } catch (Exception e) {
        log.error("\nFatal Error:" + e.getMessage());
        running = false;
    } finally {
        try {
            if (connectionSocket != null) {
                connectionSocket.close();
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error while shutting down server sockets", e);
        }
    }
}

From source file:lockstep.LockstepServer.java

/**
 * Implements the handshake protocol server side, setting up the UDP 
 * connection, queues and threads for a specific client.
 * To be run in parallel threads, one for each client, as they need
 * to synchronize to correctly setup the lockstep protocol.
 * It signals success through a latch or failure through interruption to the
 * server thread.//ww w .j a  v  a  2 s  .  co  m
 * 
 * @param tcpSocket Connection with the client, to be used in handshake only
 * @param firstFrameNumber Frame number to initialize the lockstep protocol
 * @param barrier Used for synchronization with concurrent handshake sessions
 * @param latch Used to signal the successful completion of the handshake session.
 * @param server Used to signal failure of the handshake sessions, via interruption.
 */
private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier,
        CountDownLatch latch, LockstepServer server) {
    try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) {
        oout.flush();
        try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) {
            //Receive hello message from client and reply
            LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress());
            oout.flush();
            ClientHello hello = (ClientHello) oin.readObject();
            LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress());
            DatagramSocket udpSocket = new DatagramSocket();
            openSockets.add(udpSocket);
            InetSocketAddress clientUDPAddress = new InetSocketAddress(
                    tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort);
            udpSocket.connect(clientUDPAddress);

            int assignedClientID;
            do {
                assignedClientID = (new Random()).nextInt(100000) + 10000;
            } while (!this.clientIDs.add(assignedClientID));

            LOG.info("Assigned hostID " + assignedClientID + " to "
                    + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply");
            ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID,
                    clientsNumber, firstFrameNumber);
            oout.writeObject(helloReply);

            ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>();
            this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues);

            ACKSet clientAckQueue = new ACKSet();
            ackQueues.put(assignedClientID, clientAckQueue);

            clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues);

            barrier.await();

            //Send second reply
            ClientsAnnouncement announcement = new ClientsAnnouncement();
            announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0]));
            oout.writeObject(announcement);

            clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket,
                    clientTransmissionFrameQueues);

            //Wait for other handshakes to reach final step
            barrier.await();
            oout.writeObject(new SimulationStart());

            //Continue with execution
            latch.countDown();
        }
    } catch (IOException | ClassNotFoundException ioEx) {
        LOG.fatal("Exception at handshake with client");
        LOG.fatal(ioEx);
        server.interrupt();
    } catch (InterruptedException | BrokenBarrierException inEx) {
        //Interruptions come from failure in parallel handshake sessions, and signal termination
    }
}