Java Code Examples for java.net.Socket#getLocalSocketAddress()

The following examples show how to use java.net.Socket#getLocalSocketAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BHttpConnectionBase.java    From java-android-websocket-client with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    final Socket socket = this.socketHolder.get();
    if (socket != null) {
        final StringBuilder buffer = new StringBuilder();
        final SocketAddress remoteAddress = socket.getRemoteSocketAddress();
        final SocketAddress localAddress = socket.getLocalSocketAddress();
        if (remoteAddress != null && localAddress != null) {
            NetUtils.formatAddress(buffer, localAddress);
            buffer.append("<->");
            NetUtils.formatAddress(buffer, remoteAddress);
        }
        return buffer.toString();
    } else {
        return "[Not bound]";
    }
}
 
Example 2
Source File: TransportStartpointTCP.java    From BiglyBT with GNU General Public License v2.0 6 votes vote down vote up
@Override
public InetSocketAddress
getAddress()
{
	SocketChannel channel = ep.getSocketChannel();

	if ( channel != null ){

		Socket socket = channel.socket();

		if ( socket != null ){

			return((InetSocketAddress)socket.getLocalSocketAddress());
		}
	}

	return( null );
}
 
Example 3
Source File: SocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testStateAfterClose() throws Exception {
    Socket s = new Socket();
    try {
      s.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0));
    } catch (BindException e) {
      // Continuous build environment doesn't support localhost sockets.
      return;
    }
    InetSocketAddress boundAddress = (InetSocketAddress) s.getLocalSocketAddress();
    s.close();

    assertTrue(s.isBound());
    assertTrue(s.isClosed());
    assertFalse(s.isConnected());
    assertTrue(s.getLocalAddress().isAnyLocalAddress());
    assertEquals(boundAddress.getPort(), s.getLocalPort());

    InetSocketAddress localAddressAfterClose = (InetSocketAddress) s.getLocalSocketAddress();
    assertTrue(localAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(boundAddress.getPort(), localAddressAfterClose.getPort());
}
 
Example 4
Source File: AbstractMqttChannel.java    From xenqtt with Apache License 2.0 6 votes vote down vote up
/**
 * @see net.xenqtt.message.MqttChannel#getLocalAddress()
 */
@Override
public String getLocalAddress() {

	if (localAddress == null) {
		Socket socket = channel.socket();
		if (!channel.isOpen()) {
			return "N/A";
		}

		SocketAddress address = socket.getLocalSocketAddress();
		if (address == null) {
			return "N/A";
		}
		localAddress = address.toString();
	}

	return localAddress;
}
 
Example 5
Source File: TransportStartpointTCP.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
public InetSocketAddress 
getAddress() 
{
	SocketChannel channel = ep.getSocketChannel();
	
	if ( channel != null ){
		
		Socket socket = channel.socket();
		
		if ( socket != null ){
			
			return((InetSocketAddress)socket.getLocalSocketAddress());
		}
	}
	
	return( null );
}
 
Example 6
Source File: SocketWrapperBar.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the server port that accepted the request.
 */
@Override
public InetSocketAddress ipLocal()
{
  Socket s = getSocket();
  
  if (s != null) {
    return (InetSocketAddress) s.getLocalSocketAddress();
  }
  else {
    return null;
  }
}
 
Example 7
Source File: BioSocketChannel.java    From canal with Apache License 2.0 5 votes vote down vote up
public SocketAddress getLocalSocketAddress() {
    Socket socket = this.socket;
    if (socket != null) {
        return socket.getLocalSocketAddress();
    }

    return null;
}
 
Example 8
Source File: ActiveMQMessageConsumerDispatchInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private String getEndPoint(Transport transport) {
    if (transport instanceof SocketGetter) {
        Socket socket = ((SocketGetter) transport)._$PINPOINT$_getSocket();
        SocketAddress localSocketAddress = socket.getLocalSocketAddress();
        return ActiveMQClientUtils.getEndPoint(localSocketAddress);
    } else if (transport instanceof URIGetter) {
        URI uri = ((URIGetter) transport)._$PINPOINT$_getUri();
        return HostAndPort.toHostAndPortString(uri.getHost(), uri.getPort());
    }
    return null;
}
 
Example 9
Source File: BlurClientManager.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static String getConnectionStr(Client client) {
  TTransport transport = client.getInputProtocol().getTransport();
  if (transport instanceof TFramedTransport) {
    TFramedTransport framedTransport = (TFramedTransport) transport;
    transport = framedTransport.getTransport();
  }
  if (transport instanceof TSocket) {
    TSocket tsocket = (TSocket) transport;
    Socket socket = tsocket.getSocket();
    SocketAddress localSocketAddress = socket.getLocalSocketAddress();
    SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
    return localSocketAddress.toString() + ":" + remoteSocketAddress.toString();
  }
  return "unknown";
}
 
Example 10
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void assertSocketAfterImplicitBind(Socket s) throws IOException {
    assertTrue(s.isBound());
    assertTrue(s.getLocalAddress().isLoopbackAddress());
    assertTrue(s.getLocalPort() > 0);

    InetSocketAddress localSocketAddress = (InetSocketAddress) s.getLocalSocketAddress();
    assertTrue(localSocketAddress.getAddress().isLoopbackAddress());
    assertEquals(s.getLocalPort(), localSocketAddress.getPort());
}
 
Example 11
Source File: BioSocketChannel.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public SocketAddress getLocalSocketAddress() {
    Socket socket = this.socket;
    if (socket != null) {
        return socket.getLocalSocketAddress();
    }

    return null;
}
 
Example 12
Source File: PyroClient.java    From TelegramApi with MIT License 5 votes vote down vote up
/**
 * Returns the local socket address (host+port)
 */

public InetSocketAddress getLocalAddress()
{
   Socket s = ((SocketChannel) key.channel()).socket();
   return (InetSocketAddress) s.getLocalSocketAddress();
}
 
Example 13
Source File: TCPTunneler.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public StreamForwarder(Socket input,
                       Socket output,
                       final int bufferSize,
                       final ForwardCallback forwardCallback) throws IOException
{
    _inputStream = input.getInputStream();
    _outputStream = output.getOutputStream();
    _forwardCallback = forwardCallback == null ? numberOfBytesForwarded -> {} : forwardCallback;
    _name = "Forwarder-" + input.getLocalSocketAddress() + "->" + output.getRemoteSocketAddress();
    _bufferSize = bufferSize;
}
 
Example 14
Source File: NioSocketSession.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public InetSocketAddress getLocalAddress() {
    if (channel == null) {
        return null;
    }

    Socket socket = getSocket();

    if (socket == null) {
        return null;
    }

    return (InetSocketAddress) socket.getLocalSocketAddress();
}
 
Example 15
Source File: ClientPool.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
private String getIdentifer(Socket socket) {
  SocketAddress localSocketAddress = socket.getLocalSocketAddress();
  SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
  return localSocketAddress.toString() + " -> " + remoteSocketAddress.toString();
}
 
Example 16
Source File: BIOSocketServerListener.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void run()
{
    try
    {
        while (true)
        {
            //
            // Set up HTTP connection
            //
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "waiting for a connection on socket");
            Socket socket = serverSocket.accept();
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "got a connection");
            
            Http1Config h1c = Http1Config.custom()
            		.build();
            
            DefaultBHttpServerConnection serverConnection = null;
            
            if (secure) {
            	serverConnection = new DefaultBHttpServerConnection("https", h1c);
            }else {
            	serverConnection = new DefaultBHttpServerConnection("http", h1c);
            }
            serverConnection.bind(socket);
            
            InetSocketAddress remoteInetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
            InetSocketAddress localInetSocketAddress = (InetSocketAddress) socket.getLocalSocketAddress();
            
            String connectionName = "HTTPServerConnection" + Stack.nextTransactionId();
            String remoteHost = remoteInetSocketAddress.getAddress().getHostAddress();
            String remotePort = Integer.toString(remoteInetSocketAddress.getPort());
            String localHost = localInetSocketAddress.getAddress().getHostAddress();
            String localPort = Integer.toString(localInetSocketAddress.getPort());
            
            BIOChannelHttp connHttp = new BIOChannelHttp(connectionName, localHost, localPort, remoteHost, remotePort, StackFactory.PROTOCOL_HTTP, secure);
            
            //
            // Start Server thread
            //
            BIOSocketServerHttp socketServerHttp = new BIOSocketServerHttp(serverConnection, connHttp);

            connHttp.setSocketServerHttp(socketServerHttp);
            StackFactory.getStack(StackFactory.PROTOCOL_HTTP).openChannel(connHttp);
        }
    }
    catch(Exception e)
    {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.PROTOCOL, e, "Exception in SocketServerListener secure=" + secure);
    }
    
    GlobalLogger.instance().getApplicationLogger().warn(TextEvent.Topic.PROTOCOL, "SocketServerListener secure=", secure, "stopped");
}
 
Example 17
Source File: BlockReader.java    From RDFS with Apache License 2.0 4 votes vote down vote up
public static BlockReader newBlockReader( int dataTransferVersion,
                                   int namespaceId,
                                   Socket sock, String file,
                                   long blockId,
                                   long genStamp,
                                   long startOffset, long len,
                                   int bufferSize, boolean verifyChecksum,
                                   String clientName, long minSpeedBps)
                                   throws IOException {
  // in and out will be closed when sock is closed (by the caller)
  DataOutputStream out = new DataOutputStream(
    new BufferedOutputStream(NetUtils.getOutputStream(sock,HdfsConstants.WRITE_TIMEOUT)));

  //write the header.
  ReadBlockHeader readBlockHeader = new ReadBlockHeader(
      dataTransferVersion, namespaceId, blockId, genStamp, startOffset, len,
      clientName);
  readBlockHeader.writeVersionAndOpCode(out);
  readBlockHeader.write(out);
  out.flush();

  //
  // Get bytes in block, set streams
  //

  DataInputStream in = new DataInputStream(
      new BufferedInputStream(NetUtils.getInputStream(sock),
                              bufferSize));

  if ( in.readShort() != DataTransferProtocol.OP_STATUS_SUCCESS ) {
    throw new IOException("Got error in response to OP_READ_BLOCK " +
                          "self=" + sock.getLocalSocketAddress() +
                          ", remote=" + sock.getRemoteSocketAddress() +
                          " for file " + file +
                          " for block " + blockId);
  }
  DataChecksum checksum = DataChecksum.newDataChecksum( in , new PureJavaCrc32());
  //Warning when we get CHECKSUM_NULL?

  // Read the first chunk offset.
  long firstChunkOffset = in.readLong();

  if ( firstChunkOffset < 0 || firstChunkOffset > startOffset ||
      firstChunkOffset >= (startOffset + checksum.getBytesPerChecksum())) {
    throw new IOException("BlockReader: error in first chunk offset (" +
                          firstChunkOffset + ") startOffset is " +
                          startOffset + " for file " + file);
  }

  return new BlockReader(file, blockId, in, checksum, verifyChecksum,
      startOffset, firstChunkOffset, sock, minSpeedBps, dataTransferVersion);
}
 
Example 18
Source File: PhysicalConnection.java    From ClickHouse-Native-JDBC with Apache License 2.0 4 votes vote down vote up
public PhysicalConnection(Socket socket, BinarySerializer serializer, BinaryDeserializer deserializer) {
    this.socket = socket;
    this.serializer = serializer;
    this.deserializer = deserializer;
    this.address = socket.getLocalSocketAddress();
}
 
Example 19
Source File: TransportStartpointTCP.java    From BiglyBT with GNU General Public License v2.0 3 votes vote down vote up
@Override
public InetSocketAddress
getNotionalAddress()
{
	SocketChannel channel = ep.getSocketChannel();

	if ( channel != null ){

		Socket socket = channel.socket();

		if ( socket != null ){

		    AEProxyAddressMapper.AppliedPortMapping applied_mapping = proxy_address_mapper.applyPortMapping( socket.getInetAddress(), socket.getPort());

		    InetSocketAddress	tcp_address = applied_mapping.getLocalAddress();
		    
		    if ( tcp_address != null ){
		    
		    	return( tcp_address );
		    }
		    
		    return((InetSocketAddress)socket.getLocalSocketAddress());
		}
	}

	return( null );
}