List of usage examples for java.net Socket getLocalPort
public int getLocalPort()
From source file:org.unitime.timetable.solver.remote.RemoteSolverServerProxy.java
public Object query(Object command) throws Exception { Socket socket = null; try {/*ww w . ja v a 2 s . c om*/ socket = leaseConnection(); sLog.debug("-- connection (" + iLeasedSockets.size() + ") " + this + "@" + socket.getLocalPort() + " leased"); Object answer = null; RemoteIo.writeObject(socket, command); //sLog.debug("Q:"+(command instanceof Object[]?((Object[])command)[0]:command)); try { answer = RemoteIo.readObject(socket); } catch (java.io.EOFException ex) { } ; //sLog.debug("A:"+answer); //disconnect(); if (answer != null && answer instanceof Exception) throw (Exception) answer; return answer; } catch (SocketException e) { disconnectProxy(); sLog.error("Unable to query, reason: " + e.getMessage()); return null; } finally { if (socket != null) { releaseConnection(socket); sLog.debug("-- connection (" + iLeasedSockets.size() + ") " + this + "@" + socket.getLocalPort() + " released"); } } }
From source file:org.unitime.timetable.solver.remote.RemoteSolverServerProxy.java
public Socket leaseConnection() throws Exception { synchronized (iSocketPool) { if (iSocketPool.isEmpty() && iSocketPool.size() + iLeasedSockets.size() < sMaxPoolSize) { Socket socket = ConnectionFactory.getSocketFactory().createSocket(iAddress.getHostName(), iPort); ;/*from w w w.j ava 2s.c o m*/ sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " created"); iLeasedSockets.addElement(socket); return socket; } while (true) { if (!iSocketPool.isEmpty()) { Socket socket = (Socket) iSocketPool.firstElement(); iSocketPool.removeElement(socket); if (socket.isClosed()) { socket = ConnectionFactory.getSocketFactory().createSocket(iAddress.getHostName(), iPort); ; sLog.debug("-- connection " + this + "@" + socket.getLocalPort() + " created (reconnect)"); } iLeasedSockets.addElement(socket); return socket; } iSocketPool.wait(); } } }
From source file:org.apache.hadoop.net.TestNetUtils.java
/** * Test that we can't accidentally connect back to the connecting socket due * to a quirk in the TCP spec./*from w w w . j ava2 s. c o m*/ * * This is a regression test for HADOOP-6722. */ @Test public void testAvoidLoopbackTcpSockets() throws Exception { Configuration conf = new Configuration(); Socket socket = NetUtils.getDefaultSocketFactory(conf).createSocket(); socket.bind(new InetSocketAddress("localhost", 0)); System.err.println("local address: " + socket.getLocalAddress()); System.err.println("local port: " + socket.getLocalPort()); try { NetUtils.connect(socket, new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()), 20000); socket.close(); fail("Should not have connected"); } catch (ConnectException ce) { System.err.println("Got exception: " + ce); assertTrue(ce.getMessage().contains("resulted in a loopback")); } catch (SocketException se) { // Some TCP stacks will actually throw their own Invalid argument // exception here. This is also OK. assertTrue(se.getMessage().contains("Invalid argument")); } }
From source file:org.apache.hama.util.BSPNetUtils.java
/** * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a * local address and port to bind the socket to. * //from ww w. ja v a 2s.c o m * @param socket * @param endpoint the remote address * @param localAddr the local address to bind the socket to * @param timeout timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { socket.bind(localAddr); } 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.apache.solr.client.solrj.impl.BasicHttpSolrServerTest.java
private int findUnusedPort() { for (int port = 0; port < 65535; port++) { Socket s = new Socket(); try {/*from w w w . ja va 2 s . c o m*/ s.bind(null); int availablePort = s.getLocalPort(); s.close(); return availablePort; } catch (IOException e) { e.printStackTrace(); } } throw new RuntimeException("Could not find unused TCP port."); }
From source file:org.apache.ftpserver.ssl.Ssl.java
/** * Returns a socket layered over an existing socket. *///from w ww . j av a2 s .c om public Socket createSocket(String protocol, Socket soc, boolean clientMode) throws Exception { // already wrapped - no need to do anything if (soc instanceof SSLSocket) { return soc; } // get socket factory SSLContext ctx = getSSLContext(protocol); SSLSocketFactory socFactory = ctx.getSocketFactory(); // create socket String host = soc.getInetAddress().getHostAddress(); int port = soc.getLocalPort(); SSLSocket ssoc = (SSLSocket) socFactory.createSocket(soc, host, port, true); ssoc.setUseClientMode(clientMode); // initialize socket String cipherSuites[] = ssoc.getSupportedCipherSuites(); ssoc.setEnabledCipherSuites(cipherSuites); ssoc.setNeedClientAuth(m_clientAuthReqd); return ssoc; }
From source file:com.mirth.connect.server.util.ConnectorUtil.java
public static ConnectionTestResponse testConnection(String host, int port, int timeout, String localAddr, int localPort) throws Exception { Socket socket = null; InetSocketAddress address = null; InetSocketAddress localAddress = null; try {//from w w w.j a v a 2 s. c om address = new InetSocketAddress(host, port); if (StringUtils.isBlank(address.getAddress().getHostAddress()) || (address.getPort() < 0) || (address.getPort() > 65534)) { throw new Exception(); } } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid host or port."); } if (localAddr != null) { try { localAddress = new InetSocketAddress(localAddr, localPort); if (StringUtils.isBlank(localAddress.getAddress().getHostAddress()) || (localAddress.getPort() < 0) || (localAddress.getPort() > 65534)) { throw new Exception(); } } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid local host or port."); } } try { socket = new Socket(); if (localAddress != null) { try { socket.bind(localAddress); } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not bind to local address: " + localAddress.getAddress().getHostAddress() + ":" + localAddress.getPort()); } } socket.connect(address, timeout); String connectionInfo = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " -> " + address.getAddress().getHostAddress() + ":" + address.getPort(); return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS, "Successfully connected to host: " + connectionInfo, connectionInfo); } catch (SocketTimeoutException ste) { return new ConnectionTestResponse(ConnectionTestResponse.Type.TIME_OUT, "Timed out connecting to host: " + address.getAddress().getHostAddress() + ":" + address.getPort()); } catch (Exception e) { return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not connect to host: " + address.getAddress().getHostAddress() + ":" + address.getPort()); } finally { if (socket != null) { socket.close(); } } }
From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java
private void startSyncing() { final String syncHost = config.getString("fileserver.sync-host", DEFAULT_HOST); final int syncPort = config.getInt("fileserver.sync-port", DEFAULT_SYNC_PORT); final int connectionTimeout = config.getInt("fileserver.connection.timeout", 5000); LOG.info("preparing to sync to secondary server on " + syncHost + " port " + syncPort); final InetAddress address; try {/*ww w .ja va2 s . com*/ address = InetAddress.getByName(syncHost); } catch (final UnknownHostException e) { LOG.error("Unknown host " + syncHost, e); System.exit(0); return; } while (awaitConnections) { Socket socket = null; try { socket = new Socket(address, syncPort); LOG.info("sync connected to " + socket.getInetAddress().getHostAddress() + " port " + socket.getLocalPort()); final CRC32 crc32 = new CRC32(); final DataOutput output = new DataOutputStream( new CheckedOutputStream(socket.getOutputStream(), crc32)); final DataInput input = new DataInputStream(socket.getInputStream()); output.writeByte(INIT); long logId = input.readLong(); do { final long nextLogId = logId + 1; final File file = Util.logFile(nextLogId); if (file.exists() && server.getLogger().isWritten(nextLogId)) { logId++; output.writeByte(RECOVERY_LOG); crc32.reset(); output.writeLong(logId); LOG.info("sending recovery file: " + file.getName()); final BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file)); final byte[] buffer = new byte[8092]; int read; while ((read = fileInput.read(buffer)) > 0) { output.writeInt(read); output.write(buffer, 0, read); } output.writeInt(0); output.writeLong(crc32.getValue()); } try { Thread.sleep(300); } catch (final InterruptedException ignore) { } while (isQuiescent) { try { Thread.sleep(300); } catch (final InterruptedException ignore) { } } } while (awaitConnections); } catch (final ConnectException e) { LOG.warn("not yet connected to secondary server at " + syncHost + " port " + syncPort); try { Thread.sleep(connectionTimeout); } catch (final InterruptedException ignore) { } } catch (final IOException e) { LOG.error("start failure - networking not set up for " + syncHost, e); try { Thread.sleep(300); } catch (final InterruptedException ignore) { } } catch (final RuntimeException e) { LOG.error("start failure", e); try { Thread.sleep(300); } catch (final InterruptedException ignore) { } } } }
From source file:org.pepstock.jem.gwt.server.connector.WebInterceptor.java
@Override public void onConnect(Socket connectedSocket) throws IOException { LogAppl.getInstance().emit(NodeMessage.JEMC202I); PrintWriter out = null;/*from ww w.ja va 2s.c o m*/ BufferedReader in = null; String address = null; try { // get the printer to use to send the request to the server out = new PrintWriter(new OutputStreamWriter(connectedSocket.getOutputStream(), CharSet.DEFAULT)); // get the reader to use to read the response sent from the server in = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream(), CharSet.DEFAULT)); // is the ip seen from the server String ip = connectedSocket.getLocalAddress().getHostAddress(); // is the port seen from the server int port = connectedSocket.getLocalPort(); address = ip + ":" + port; // if it must read the keystore // form servlet context if (readKeyStore) { readKeyStore(); } // instantiate the jemProtocol that give the right request (Base64 // encoded) from the given response Key symmetricKey = KeysUtil.getSymmetricKey(clusterKeystoreInfo); ClientLoginProtocol jemClientProtocol = new ClientLoginProtocol(symmetricKey); String request = jemClientProtocol.getRequestFromResponse(null, address, LoginRequest.JEM_WEB_USER); LogAppl.getInstance().emit(NodeMessage.JEMC203I, new String(Base64.decode(request), CharSet.DEFAULT)); out.println(request); out.flush(); String inputResponse; String outputRequest; while ((inputResponse = in.readLine()) != null) { outputRequest = jemClientProtocol.getRequestFromResponse(inputResponse, address, LoginRequest.JEM_WEB_USER); LogAppl.getInstance().emit(NodeMessage.JEMC203I, new String(Base64.decode(inputResponse), CharSet.DEFAULT)); if (outputRequest != null) { LogAppl.getInstance().emit(NodeMessage.JEMC203I, new String(Base64.decode(outputRequest), CharSet.DEFAULT)); } if (jemClientProtocol.isConversationTerminated()) { break; } out.println(outputRequest); out.flush(); } } catch (LoginProtocolException e) { LogAppl.getInstance().emit(NodeMessage.JEMC106W, e); throw new IOException(e.getMessage(), e); } catch (KeyException e) { LogAppl.getInstance().emit(NodeMessage.JEMC106W, e); throw new IOException(e.getMessage(), e); } }
From source file:com.buaa.cfs.utils.NetUtils.java
/** * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the * socket to.//w w w. j a v a 2s . c om * * @param socket * @param endpoint the remote address * @param localAddr the local address to bind the socket to * @param timeout timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { Class localClass = localAddr.getClass(); Class remoteClass = endpoint.getClass(); Preconditions.checkArgument(localClass.equals(remoteClass), "Local address %s must be of same family as remote address %s.", localAddr, endpoint); socket.bind(localAddr); } try { if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { // SocketIOWithTimeout.connect(ch, endpoint, timeout); } } catch (SocketTimeoutException ste) { // throw new ConnectTimeoutException(ste.getMessage()); } // 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."); } }