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.msec.LogsysProxy.java

public static void main(String[] args) {

    try {/*from   www . j a  v  a  2s  . c  o m*/
        Options options = new Options();
        Option option = new Option("c", "conf", true, "configuration filename");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("h", "help", false, "show help");
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = null;

        try {
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println("Parse command line failed.");
            e.printStackTrace();
            return;
        }

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("LogsysProxy", options, true);
            return;
        }

        //
        String conFilename = commandLine.getOptionValue('c');
        String userdir = System.getProperty("user.dir");
        Properties props = new Properties();
        InputStream in = new FileInputStream(conFilename);
        props.load(in);
        in.close();

        PropertyConfigurator.configure("conf/log4j.properties");
        Class.forName("com.mysql.jdbc.Driver");

        //: 30150
        int listenPort = Integer.parseInt(props.getProperty("listen", "30150"));
        ServerSocket serverSocket = new ServerSocket(listenPort);
        Socket socket = null;

        logger.info("Logsys Proxy Started.");
        //, 
        while (true) {
            socket = serverSocket.accept();

            InetAddress address = socket.getInetAddress();
            logger.info("Request coming ... " + address.getHostAddress());
            ServerThread serverThread = new ServerThread(socket, conFilename, props);
            serverThread.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:Bounce.java

/**
 * The main method./*from w  w  w  .j  av  a 2s . c o m*/
 */

public static void main(String[] args) {
    if (args.length < 3) {
        printUsage();
        System.exit(1);
    }

    int localPort;
    try {
        localPort = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Bad local port value: " + args[0]);
        printUsage();
        System.exit(2);
        return;
    }

    String hostname = args[1];

    int remotePort;
    try {
        remotePort = Integer.parseInt(args[2]);
    } catch (NumberFormatException e) {
        System.err.println("Bad remote port value: " + args[2]);
        printUsage();
        System.exit(3);
        return;
    }

    boolean shouldLog = args.length > 3 ? Boolean.valueOf(args[3]).booleanValue() : false;
    int numConnections = 0;

    try {
        ServerSocket ssock = new ServerSocket(localPort);
        while (true) {
            Socket incomingSock = ssock.accept();
            Socket outgoingSock = new Socket(hostname, remotePort);
            numConnections++;

            InputStream incomingIn = incomingSock.getInputStream();
            InputStream outgoingIn = outgoingSock.getInputStream();
            OutputStream incomingOut = incomingSock.getOutputStream();
            OutputStream outgoingOut = outgoingSock.getOutputStream();

            if (shouldLog) {
                String incomingLogName = "in-log-" + incomingSock.getInetAddress().getHostName() + "("
                        + localPort + ")-" + numConnections + ".dat";
                String outgoingLogName = "out-log-" + hostname + "(" + remotePort + ")-" + numConnections
                        + ".dat";
                OutputStream incomingLog = new FileOutputStream(incomingLogName);
                incomingOut = new MultiOutputStream(incomingOut, incomingLog);
                OutputStream outgoingLog = new FileOutputStream(outgoingLogName);
                outgoingOut = new MultiOutputStream(outgoingOut, outgoingLog);
            }

            PumpThread t1 = new PumpThread(incomingIn, outgoingOut);
            PumpThread t2 = new PumpThread(outgoingIn, incomingOut);
            t1.start();
            t2.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {/*from  www . j  a  va2s  .c o m*/
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:com.mirth.connect.connectors.tcp.SocketUtil.java

public static String getInetAddress(Socket socket) {
    String inetAddress = socket == null || socket.getInetAddress() == null ? ""
            : socket.getInetAddress().toString() + ":" + socket.getPort();

    if (inetAddress.startsWith("/")) {
        inetAddress = inetAddress.substring(1);
    }// w ww  .  j  a va 2 s . c o  m

    return inetAddress;
}

From source file:org.huahinframework.emanager.util.StopUtils.java

/**
 * @param port/*from w w w  . ja v a 2 s .co  m*/
 * @param msg
 */
public static void stop(int port, String msg) {
    try {
        InetSocketAddress socketAddress = new InetSocketAddress("localhost", port);
        Socket socket = new Socket();
        socket.connect(socketAddress, 10000);

        InetAddress inadr = socket.getInetAddress();
        if (inadr == null) {
            log.error("connect error: " + "localhost:" + port);
            return;
        }

        PrintWriter writer = new PrintWriter(socket.getOutputStream());
        writer.println(msg);

        writer.close();
        socket.close();
    } catch (Exception e) {
        log.error(e);
        e.printStackTrace();
    }
}

From source file:com.impetus.kundera.examples.twitter.TwissandraTest.java

/**
 * Check if server running./*from w  w  w. ja va2  s  .  co m*/
 * 
 * @return true, if successful
 */

public static boolean checkIfServerRunning() {
    try {
        Socket socket = new Socket("127.0.0.1", 9165);
        return socket.getInetAddress() != null;
    } catch (UnknownHostException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.impetus.client.persistence.CassandraCli.java

/**
 * Check if server running.//  w  w w . ja  v a2s  .c o  m
 * 
 * @return true, if successful
 */
private static boolean checkIfServerRunning() {
    try {
        Socket socket = new Socket("127.0.0.1", 9160);
        return socket.getInetAddress() != null;
    } catch (UnknownHostException e) {
        return false;
    } catch (IOException e) {
        return false;
    }

}

From source file:de.hshannover.f4.trust.iron.mapserver.contentauth.RemotePDP.java

private static void runServer(int port, LocalSunXacml pdp, int threads) {
    Executor clientExec = Executors.newFixedThreadPool(threads);
    ServerSocketFactory sockFac = ServerSocketFactory.getDefault();

    try {/*from   w  ww  .  j a  va  2  s.co m*/
        ServerSocket sock = sockFac.createServerSocket(port);
        while (true) {
            Socket clientSock = sock.accept();
            Runnable cmd = new HandleXacmlRequest(clientSock, pdp);
            System.out.println(nameDate() + "new client " + clientSock.getInetAddress());
            clientExec.execute(cmd);
        }
    } catch (IOException e) {
        System.err.println(nameDate() + e.toString());
        System.exit(1);
    }
}

From source file:org.ambientdynamix.web.WebUtils.java

/**
 * Returns the RunningAppProcessInfo bound to the incoming socket. Returns null if the socket is not bound to any
 * apps./*from   w  w  w  .  j  av a2  s.  c  o  m*/
 */
public static RunningAppProcessInfo getAppProcessForSocket(Socket socket) {
    List<UidPortMapping> mappings = new ArrayList<WebUtils.UidPortMapping>();
    // Check for connection type
    if (socket.getInetAddress() instanceof java.net.Inet4Address) {
        // Map all IPV4 connections
        mappings.addAll(getUidPortMappings("/proc/net/tcp"));
    } else {
        // Map all IPV6 connections
        mappings.addAll(getUidPortMappings("/proc/net/tcp6"));
    }
    // Create the local activity manager, if needed
    if (actMgr == null) {
        // Grab the ActivityManager
        actMgr = (ActivityManager) DynamixService.getAndroidContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
    }
    /*
     * Loop through the list of running processes, looking for a UID matching one of the cached connections.
     */
    List<RunningAppProcessInfo> l = actMgr.getRunningAppProcesses();
    for (RunningAppProcessInfo app : l) {
        for (UidPortMapping connection : mappings) {
            if (connection.uid == app.uid)
                return app;
        }
    }
    Log.w(TAG, "Could not find RunningAppProcessInfo for socket " + socket);
    return null;
}

From source file:org.expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>.//  www .jav a 2 s . c  o  m
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        //System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        //System.out.println("Request sent");

        //System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            //System.out.println(line);
            //System.out.println("Received response");
            if (line == null)
                System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}