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

The following examples show how to use java.net.Socket#getLocalAddress() . 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: NetUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通过连接远程地址得到本机内网地址
 *
 * @param remoteAddress 远程地址
 * @return 本机内网地址
 */
private static InetAddress getLocalHostBySocket(InetSocketAddress remoteAddress) {
    InetAddress host = null;
    try {
        // 去连一下远程地址
        Socket socket = new Socket();
        try {
            socket.connect(remoteAddress, 1000);
            // 得到本地地址
            host = socket.getLocalAddress();
        } finally {
            IOUtils.closeQuietly(socket);
        }
    } catch (Exception e) {
        LOGGER.warn("Can not connect to host {}, cause by :{}",
            remoteAddress.toString(), e.getMessage());
    }
    return host;
}
 
Example 2
Source File: ftpConnection.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method now accepts a timeout parameter which is part of the fix for NA #3301
 */
public response open(int timeout){
  try{
    socketConnection = new Socket( hostname, hostport );
    socketConnection.setSoTimeout(timeout);
    localHost = socketConnection.getLocalAddress();
    controlInputStream = new BufferedReader( new InputStreamReader( socketConnection.getInputStream() ) );
    controlOutputStream = new PrintStream( socketConnection.getOutputStream() );
    checkResponse();
    response responseToLogin = login();
    if ( responseToLogin.getResponse() == 530 ){
      return responseToLogin;
    }
    isOpen = true;
    return responseToLogin;//checkResponse();
   }catch(IOException e){
    return null;
  }
}
 
Example 3
Source File: SocksSocket.java    From T0rlib4j with Apache License 2.0 5 votes vote down vote up
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 4
Source File: SocksSocket.java    From T0rlib4Android with Apache License 2.0 5 votes vote down vote up
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 5
Source File: OkNetworkEventListener.java    From AndroidGodEye with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionAcquired(Call call, Connection connection) {
    super.connectionAcquired(call, connection);
    Handshake handshake = connection.handshake();
    String cipherSuite = "";
    String tlsVersion = "";
    if (handshake != null) {
        cipherSuite = handshake.cipherSuite().javaName();
        tlsVersion = handshake.tlsVersion().javaName();
    }
    Socket socket = connection.socket();
    int localPort = socket.getLocalPort();
    int remotePort = socket.getPort();
    String localIp = "";
    String remoteIp = "";
    InetAddress localAddress = socket.getLocalAddress();
    if (localAddress != null) {
        localIp = localAddress.getHostAddress();
    }
    InetAddress remoteAddress = socket.getInetAddress();
    if (remoteAddress != null) {
        remoteIp = remoteAddress.getHostAddress();
    }
    mNetworkInfo.extraInfo.put("cipherSuite", cipherSuite);
    mNetworkInfo.extraInfo.put("tlsVersion", tlsVersion);
    mNetworkInfo.extraInfo.put("localIp", localIp);
    mNetworkInfo.extraInfo.put("localPort", localPort);
    mNetworkInfo.extraInfo.put("remoteIp", remoteIp);
    mNetworkInfo.extraInfo.put("remotePort", remotePort);
}
 
Example 6
Source File: SocketWrapperBar.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the server inet address that accepted the request.
 */
@Override
public InetAddress addressLocal()
{
  Socket s = getSocket();
  
  if (s != null) {
    return s.getLocalAddress();
  }
  else {
    return null;
  }
}
 
Example 7
Source File: FTP5250Prot.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set up ftp sockets and connect to an as400
 */
public boolean connect(String host, int port) {

   try {

      hostName = host;
      ftpConnectionSocket = new Socket(host, port);
      ftpConnectionSocket.setSoTimeout(timeout);
      localHost = ftpConnectionSocket.getLocalAddress();
      ftpInputStream = new BufferedReader(new InputStreamReader(ftpConnectionSocket.getInputStream()));
      ftpOutputStream = new PrintStream(ftpConnectionSocket.getOutputStream());
      parseResponse();
      fileSize = 0;

      if (lastIntResponse == 220) {
         connected = true;
         return true;
      }
      else {
         connected = false;
         return false;
      }
   }
   catch(Exception _ex) {
      return false;
   }

}
 
Example 8
Source File: SocketUtils.java    From laser with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 格式化链接输出
 *
 * @param socket socket链接
 * @return 格式化后的信息
 */
public static String format(Socket socket) {
    return "["
            + socket.getLocalAddress()
            + "->"
            + socket.getRemoteSocketAddress()
            + "]";
}
 
Example 9
Source File: RemoteSession.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private String initialize() throws UnknownHostException, IOException {
    logger.debug("Creating socket for host " + host + " on port " + port);

    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), 5000);

    logger.debug("Socket successfully created and connected");
    InetAddress localAddress = socket.getLocalAddress();
    logger.debug("Local address is " + localAddress.getHostAddress());

    logger.debug("Sending registration message");
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    writer.append((char) 0x00);
    writeText(writer, APP_STRING);
    writeText(writer, getRegistrationPayload(localAddress.getHostAddress()));
    writer.flush();

    InputStream in = socket.getInputStream();
    reader = new InputStreamReader(in);
    String result = readRegistrationReply(reader);
    // sendPart2();
    int i;
    while ((i = in.available()) > 0) {
        in.skip(i);
    }
    return result;
}
 
Example 10
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 11
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 12
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 13
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public InetSocketAddress getLocalAddress() {
   Socket s = this.connection.getChannel().socket();
   InetAddress ia = s.getLocalAddress();
   int port = s.getLocalPort();
   return new InetSocketAddress(ia, port);
}
 
Example 14
Source File: BHttpConnectionBase.java    From java-android-websocket-client with Apache License 2.0 4 votes vote down vote up
@Override
public InetAddress getLocalAddress() {
    final Socket socket = this.socketHolder.get();
    return socket != null ? socket.getLocalAddress() : null;
}
 
Example 15
Source File: RMBTTest.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
protected Socket connect(final TestResult testResult) throws IOException
{
    log(String.format(Locale.US, "thread %d: connecting...", threadId));
    
    final InetAddress inetAddress = InetAddress.getByName(params.getHost());
    
    System.out.println("connecting to: " + inetAddress.getHostName() + ":" + params.getPort());
    final Socket s = getSocket(inetAddress.getHostAddress(), params.getPort(), true, 20000);
    
    testResult.ip_local = s.getLocalAddress();
    testResult.ip_server = s.getInetAddress();
    
    testResult.port_remote = s.getPort();
    
    if (s instanceof SSLSocket)
    {
        final SSLSocket sslSocket = (SSLSocket) s;
        final SSLSession session = sslSocket.getSession();
        testResult.encryption = String.format(Locale.US, "%s (%s)", session.getProtocol(), session.getCipherSuite());
    }
    
    log(String.format(Locale.US, "thread %d: ReceiveBufferSize: '%s'.", threadId, s.getReceiveBufferSize()));
    log(String.format(Locale.US, "thread %d: SendBufferSize: '%s'.", threadId, s.getSendBufferSize()));
    
    if (in != null)
        totalDown += in.getCount();
    if (out != null)
        totalUp += out.getCount();
    
    in = new InputStreamCounter(s.getInputStream());
    reader = new BufferedReader(new InputStreamReader(in, "US-ASCII"), 4096);
    out = new OutputStreamCounter(s.getOutputStream());
    
    String line = reader.readLine();
    if (!line.equals(EXPECT_GREETING))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected '%s'", threadId, line, EXPECT_GREETING));
        return null;
    }
    
    line = reader.readLine();
    if (!line.startsWith("ACCEPT "))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected 'ACCEPT'", threadId, line));
        return null;
    }
    
    final String send = String.format(Locale.US, "TOKEN %s\n", params.getToken());
    
    out.write(send.getBytes("US-ASCII"));
    
    line = reader.readLine();
    
    if (line == null)
    {
        log(String.format(Locale.US, "thread %d: got no answer expected 'OK'", threadId, line));
        return null;
    }
    else if (!line.equals("OK"))
    {
        log(String.format(Locale.US, "thread %d: got '%s' expected 'OK'", threadId, line));
        return null;
    }
    
    line = reader.readLine();
    final Scanner scanner = new Scanner(line);
    try
    {
        if (!"CHUNKSIZE".equals(scanner.next()))
        {
            log(String.format(Locale.US, "thread %d: got '%s' expected 'CHUNKSIZE'", threadId, line));
            return null;
        }
        try
        {
            chunksize = scanner.nextInt();
            log(String.format(Locale.US, "thread %d: CHUNKSIZE is %d", threadId, chunksize));
        }
        catch (final Exception e)
        {
            log(String.format(Locale.US, "thread %d: invalid CHUNKSIZE: '%s'", threadId, line));
            return null;
        }
        if (buf == null || buf != null && buf.length != chunksize)
            buf = new byte[chunksize];
        return s;
    }
    finally
    {
        scanner.close();
    }
}
 
Example 16
Source File: MockTcpTransport.java    From crate with Apache License 2.0 4 votes vote down vote up
public void accept(Executor executor) throws IOException {
    while (isOpen.get()) {
        Socket incomingSocket = serverSocket.accept();
        MockChannel incomingChannel = null;
        try {
            configureSocket(incomingSocket);
            synchronized (this) {
                if (isOpen.get()) {
                    incomingChannel = new MockChannel(incomingSocket,
                                                      new InetSocketAddress(
                                                          incomingSocket.getLocalAddress(),
                                                          incomingSocket.getPort()
                                                      ),
                                                      profile);
                    MockChannel finalIncomingChannel = incomingChannel;
                    incomingChannel.addCloseListener(new ActionListener<Void>() {
                        @Override
                        public void onResponse(Void aVoid) {
                            workerChannels.remove(finalIncomingChannel);
                        }

                        @Override
                        public void onFailure(Exception e) {
                            workerChannels.remove(finalIncomingChannel);
                        }
                    });
                    serverAcceptedChannel(incomingChannel);
                    //establish a happens-before edge between closing and accepting a new connection
                    workerChannels.add(incomingChannel);

                    // this spawns a new thread immediately, so OK under lock
                    incomingChannel.loopRead(executor);
                    // the channel is properly registered and will be cleared by the close code.
                    incomingSocket = null;
                    incomingChannel = null;
                }
            }
        } finally {
            // ensure we don't leak sockets and channels in the failure case. Note that we null both
            // if there are no exceptions so this becomes a no op.
            IOUtils.closeWhileHandlingException(incomingSocket, incomingChannel);
        }
    }
}