Java Code Examples for java.net.Socket.getLocalPort()

The following are Jave code examples for showing how to use getLocalPort() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: T0rlib4j   File: SocksSocket.java   View Source Code Vote up 6 votes
private void doDirect() throws SocksException {
	try {
		log.debug("IP: {}_{}", remoteIP, remotePort);
		directSock = new Socket(remoteIP, remotePort);
		proxy.out = directSock.getOutputStream();
		proxy.in = directSock.getInputStream();
		proxy.proxySocket = directSock;
		localIP = directSock.getLocalAddress();
		localPort = directSock.getLocalPort();
	} catch (final IOException io_ex) {
		final int errCode = SocksProxyBase.SOCKS_DIRECT_FAILED;
		throw new SocksException(errCode, "Direct connect failed:", io_ex);
	}
}
 
Example 2
Project: fdt   File: ControlChannel.java   View Source Code Vote up 6 votes
/**
 * A remote peer connected to FDT
 *
 * @param s - the socket
 * @throws Exception - if anything goes wrong in intialization
 */
public ControlChannel(Socket s, ControlChannelNotifier notifier) throws Exception {
    try {
        this.controlSocket = s;

        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();

        this.notifier = notifier;

        initStreams();
        controlSocket.setTcpNoDelay(true);
        controlSocket.setSoTimeout(1000);

    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 3
Project: fdt   File: ControlChannel.java   View Source Code Vote up 6 votes
/**
 * @param parent
 */
public ControlChannel(GSIServer parent, Socket s, Subject peerSubject, ControlChannelNotifier notifier)
        throws Exception {
    try {

        this.controlSocket = s;
        this.subject = peerSubject;
        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();

        this.notifier = notifier;

        initStreams();
        controlSocket.setTcpNoDelay(true);
        controlSocket.setSoTimeout(1000);

    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 4
Project: fdt   File: ServerSessionManager.java   View Source Code Vote up 6 votes
public ServerSessionManager(Socket s) throws Exception {
    currentFile = local.getHomeDirectory();
    this.currentDir = currentFile.getAbsolutePath();
    osName = System.getProperty("os.name");
    userDir = System.getProperty("user.home");
    fileSeparator = System.getProperty("file.separator");
    update();
    try {
        this.controlSocket = s;
        this.remoteAddress = s.getInetAddress();
        this.remotePort = s.getPort();
        this.localPort = s.getLocalPort();
        initStreams();
        controlSocket.setSoTimeout(1000);
    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 5
Project: GitHub   File: RecordedRequest.java   View Source Code Vote up 5 votes
public RecordedRequest(String requestLine, Headers headers, List<Integer> chunkSizes,
    long bodySize, Buffer body, int sequenceNumber, Socket socket) {
  this.requestLine = requestLine;
  this.headers = headers;
  this.chunkSizes = chunkSizes;
  this.bodySize = bodySize;
  this.body = body;
  this.sequenceNumber = sequenceNumber;
  this.tlsVersion = socket instanceof SSLSocket
      ? TlsVersion.forJavaName(((SSLSocket) socket).getSession().getProtocol())
      : null;

  if (requestLine != null) {
    int methodEnd = requestLine.indexOf(' ');
    int pathEnd = requestLine.indexOf(' ', methodEnd + 1);
    this.method = requestLine.substring(0, methodEnd);
    this.path = requestLine.substring(methodEnd + 1, pathEnd);

    String scheme = socket instanceof SSLSocket ? "https" : "http";
    String hostname = socket.getInetAddress().getHostName();
    int port = socket.getLocalPort();
    this.requestUrl = HttpUrl.parse(String.format("%s://%s:%s%s", scheme, hostname, port, path));
  } else {
    this.requestUrl = null;
    this.method = null;
    this.path = null;
  }
}
 
Example 6
Project: GitHub   File: RecordedRequest.java   View Source Code Vote up 5 votes
public RecordedRequest(String requestLine, Headers headers, List<Integer> chunkSizes,
    long bodySize, Buffer body, int sequenceNumber, Socket socket) {
  this.requestLine = requestLine;
  this.headers = headers;
  this.chunkSizes = chunkSizes;
  this.bodySize = bodySize;
  this.body = body;
  this.sequenceNumber = sequenceNumber;
  this.tlsVersion = socket instanceof SSLSocket
      ? TlsVersion.forJavaName(((SSLSocket) socket).getSession().getProtocol())
      : null;

  if (requestLine != null) {
    int methodEnd = requestLine.indexOf(' ');
    int pathEnd = requestLine.indexOf(' ', methodEnd + 1);
    this.method = requestLine.substring(0, methodEnd);
    this.path = requestLine.substring(methodEnd + 1, pathEnd);

    String scheme = socket instanceof SSLSocket ? "https" : "http";
    String hostname = socket.getInetAddress().getHostName();
    int port = socket.getLocalPort();
    this.requestUrl = HttpUrl.parse(String.format("%s://%s:%s%s", scheme, hostname, port, path));
  } else {
    this.requestUrl = null;
    this.method = null;
    this.path = null;
  }
}
 
Example 7
Project: T0rlib4Android   File: SocksSocket.java   View Source Code Vote up 5 votes
private void doDirect() throws SocksException {
	try {
		log.debug("IP: {}_{}", remoteIP, remotePort);
		directSock = new Socket(remoteIP, remotePort);
		proxy.out = directSock.getOutputStream();
		proxy.in = directSock.getInputStream();
		proxy.proxySocket = directSock;
		localIP = directSock.getLocalAddress();
		localPort = directSock.getLocalPort();
	} catch (final IOException io_ex) {
		final int errCode = SocksProxyBase.SOCKS_DIRECT_FAILED;
		throw new SocksException(errCode, "Direct connect failed:", io_ex);
	}
}
 
Example 8
Project: fdt   File: GUIControlChannel.java   View Source Code Vote up 5 votes
/**
 * Try to connect to a remote FDT instance
 *
 * @param inetAddress
 * @param port
 * @param notifier
 * @throws Exception
 */
public GUIControlChannel(InetAddress inetAddress, int port, GUIControlChannelNotifier notifier) throws Exception {
    try {
        this.notifier = notifier;

        controlSocket = new Socket();
        controlSocket.connect(new InetSocketAddress(inetAddress, port), CONNECT_TIMEOUT);

        this.remoteAddress = inetAddress;
        this.remotePort = port;
        this.localPort = controlSocket.getLocalPort();

        controlSocket.setTcpNoDelay(true);

        //only the first octet will be interpreted by the AcceptTask at the other end
        controlSocket.getOutputStream().write(new byte[]{3});

        //from now on only CtrlMsg will be sent
        initStreams();
        controlSocket.setSoTimeout(1000);

        //
    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 9
Project: openjdk-jdk10   File: TestSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Construct a socket that interposes on a socket to match and replace.
 * @param socket the underlying socket
 * @param triggerBytes array of bytes to enable matching
 * @param matchBytes the bytes that must match
 * @param replaceBytes the replacement bytes
 */
public InterposeSocket(Socket socket, byte[]
        triggerBytes, byte[] matchBytes, byte[] replaceBytes) {
    this.socket = socket;
    this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
    this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
    this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
    this.inLogStream = new ByteArrayOutputStream();
    this.outLogStream = new ByteArrayOutputStream();
    this.name = "IS" + ++num + "::"
            + Thread.currentThread().getName() + ": "
            + socket.getLocalPort() + " <  " + socket.getPort();
}
 
Example 10
Project: incubator-netbeans   File: AgentWorker.java   View Source Code Vote up 4 votes
public AgentWorker(NbJShellAgent agent, Socket controlSocket) {
    this.agent = agent;
    this.socket = controlSocket;
    this.socketPort = controlSocket.getLocalPort();
    setup();
}
 
Example 11
Project: hadoop-oss   File: NetUtils.java   View Source Code Vote up 4 votes
/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but
 * also takes a local address and port to bind the socket to. 
 * 
 * @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.");
  }
}
 
Example 12
Project: hadoop   File: NetUtils.java   View Source Code Vote up 4 votes
/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but
 * also takes a local address and port to bind the socket to. 
 * 
 * @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.");
  }
}
 
Example 13
Project: java-android-websocket-client   File: BHttpConnectionBase.java   View Source Code Vote up 4 votes
@Override
public int getLocalPort() {
    final Socket socket = this.socketHolder.get();
    return socket != null ? socket.getLocalPort() : -1;
}
 
Example 14
Project: lighthouse   File: BHttpConnectionBase.java   View Source Code Vote up 4 votes
@Override
public int getLocalPort() {
    final Socket socket = this.socketHolder.get();
    return socket != null ? socket.getLocalPort() : -1;
}
 
Example 15
Project: can4eve   File: ElmSimulator.java   View Source Code Vote up 2 votes
/**
 * return the connection for the given ClientSocket
 * 
 * @param clientSocket
 * @return the connection
 */
public ELM327SimulatorConnection getSimulatorConnection(Socket clientSocket) {
  int clientPort = clientSocket.getLocalPort();
  ELM327SimulatorConnection con = simulatorConnectionsByPort.get(clientPort);
  return con;
}