Example usage for java.net Socket getLocalPort

List of usage examples for java.net Socket getLocalPort

Introduction

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

Prototype

public int getLocalPort() 

Source Link

Document

Returns the local port number to which this socket is bound.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket client = new Socket("google.com", 80);

    System.out.println(client.getLocalPort());

    client.close();//from   w  w  w. ja va2 s  . c  om
}

From source file:getSocketInfo.java

public static void main(String[] args) {

    for (int i = 0; i < args.length; i++) {
        try {//from w  w w  . ja v  a 2 s.  co m
            Socket theSocket = new Socket(args[i], 80);
            System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()
                    + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
        } // end try
        catch (UnknownHostException e) {
            System.err.println("I can't find " + args[i]);
        } catch (SocketException e) {
            System.err.println("Could not connect to " + args[i]);
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    int port = 2345;
    ServerSocket ss = new ServerSocket(port);
    while (true) {
        try {/*  w  w w.  j a  v  a  2  s .  co  m*/
            Socket s = ss.accept();

            String response = "Hello " + s.getInetAddress() + " on port " + s.getPort() + "\r\n";
            response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort() + "\r\n";
            OutputStream out = s.getOutputStream();
            out.write(response.getBytes("US-ASCII"));
            out.flush();
            s.close();
        } catch (IOException ex) {
        }
    }
}

From source file:net.ruthandtodd.gpssync.rkoauth.RunkeeperOAuthClient.java

private static int getEphemeralPort() throws IOException {
    Socket s = new Socket();
    s.bind(null);/*from ww  w. java  2s  .  c  o m*/
    try {
        return s.getLocalPort();
    } finally {
        s.close();
    }
}

From source file:Main.java

/**
 * Renders the details of a socket in the returned string
 * @param socket The socket to render/*from   w ww .j a  va2  s  .c  o m*/
 * @return the details of the socket as a string
 */
public static String render(Socket socket) {
    if (socket == null)
        return "NULL";
    StringBuilder b = new StringBuilder("\nSocket [");
    b.append("\n\tLocalPort:").append(socket.getLocalPort());
    b.append("\n\tLocalAddress:").append(socket.getLocalAddress());
    b.append("\n\tLocalSocketAddress:").append(socket.getLocalSocketAddress());
    b.append("\n\tRemotePort:").append(socket.getPort());
    b.append("\n\tRemoteAddress:").append(socket.getInetAddress());
    b.append("\n\tRemoteSocketAddress:").append(socket.getRemoteSocketAddress());
    b.append("\n\tChannel:").append(socket.getChannel());
    b.append("\n\tHashCode:").append(socket.hashCode());
    b.append("\n]");
    return b.toString();
}

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

public static String getLocalAddress(Socket socket) {
    String localAddress = socket == null || socket.getLocalAddress() == null ? ""
            : socket.getLocalAddress().toString() + ":" + socket.getLocalPort();

    // If addresses begin with a slash "/", remove it.
    if (localAddress.startsWith("/")) {
        localAddress = localAddress.substring(1);
    }/*from  www . ja v a  2 s  . com*/

    return localAddress;
}

From source file:net.oauth.client.httpclient4.OAuthSchemeTest.java

@Override
public void setUp() throws Exception {
    { // Get an ephemeral local port number:
        Socket s = new Socket();
        s.bind(null);//from  ww w  .j a  v a  2 s .co m
        port = s.getLocalPort();
        s.close();
    }
    server = new Server(port);
    Context servletContext = new Context(server, "/", Context.SESSIONS);
    servletContext.addServlet(new ServletHolder(new ProtectedResource()), "/Resource/*");
    server.start();
    context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(OAuthSchemeFactory.SCHEME_NAME));
    client = new DefaultHttpClient();
    client.getAuthSchemes().register(OAuthSchemeFactory.SCHEME_NAME, new OAuthSchemeFactory());
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new OAuthCredentials(ProtectedResource.ACCESSOR));
}

From source file:com.sittinglittleduck.DirBuster.EasySSLProtocolSocketFactoryUnitTest.java

@Test
public void shouldCreateSocketWithGivenLocalAddressAndPort() throws Exception {
    // Given//from  www .j  a  va  2  s  .co  m
    InetAddress localAddress = InetAddress.getLoopbackAddress();
    int localPort = 28080;
    // When
    Socket sslSocket = socketFactory.createSocket("localhost", 18080, localAddress, localPort,
            new HttpConnectionParams());
    // Then
    assertThat(sslSocket.getLocalAddress(), is(equalTo(localAddress)));
    assertThat(sslSocket.getLocalPort(), is(equalTo(localPort)));
}

From source file:net.NetUtils.java

/**
 * This is a drop-in replacement for /* w  w w .  ja  v a 2  s  .c o  m*/
 * {@link Socket#connect(SocketAddress, int)}.
 * In the case of normal sockets that don't have associated channels, this 
 * just invokes <code>socket.connect(endpoint, timeout)</code>. If 
 * <code>socket.getChannel()</code> returns a non-null channel,
 * connect is implemented using Hadoop's selectors. This is done mainly
 * to avoid Sun's connect implementation from creating thread-local 
 * selectors, since Hadoop does not have control on when these are closed
 * and could end up taking all the available file descriptors.
 * 
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * 
 * @param socket
 * @param endpoint 
 * @param timeout - timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:org.unitime.timetable.solver.remote.RemoteSolverServerProxy.java

public void disconnect() {
    synchronized (iSocketPool) {
        for (Enumeration e = iSocketPool.elements(); e.hasMoreElements();) {
            Socket socket = (Socket) e.nextElement();
            try {
                sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " closed");
                socket.close();/*from   w  ww  .  ja v a  2  s. com*/
            } catch (Exception x) {
            }
        }
        iSocketPool.clear();
        for (Enumeration e = iLeasedSockets.elements(); e.hasMoreElements();) {
            Socket socket = (Socket) e.nextElement();
            try {
                sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " closed");
                socket.close();
            } catch (Exception x) {
            }
        }
        iLeasedSockets.clear();
    }
}