Java Code Examples for java.net.InetSocketAddress#getPort()

The following examples show how to use java.net.InetSocketAddress#getPort() . 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: HttpsCreateSockTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
void doClient() throws IOException {
    InetSocketAddress address = httpsServer.getAddress();

    URL url = new URL("https://localhost:" + address.getPort() + "/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    uc.setHostnameVerifier(new AllHostnameVerifier());
    if (uc instanceof javax.net.ssl.HttpsURLConnection) {
        ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory());
        System.out.println("Using TestSocketFactory");
    }
    uc.connect();
    System.out.println("CONNECTED " + uc);
    System.out.println(uc.getResponseMessage());
    uc.disconnect();
}
 
Example 2
Source File: ProxyPingHandlerTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoHandle() {
    Channel channel = mock(Channel.class);
    InetSocketAddress addr = new InetSocketAddress("127.0.0.1", randomPort());
    when(channel.localAddress()).thenReturn(addr);
    AtomicReference<String> actual = new AtomicReference<>();
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            actual.set(new SimpleStringParser().read(invocation.getArgumentAt(0, ByteBuf.class)).getPayload());
            return null;
        }
    }).when(channel).writeAndFlush(any(ByteBuf.class));
    handler.handle(channel, new String[]{"PING"});
    String expected = "PROXY PONG 127.0.0.1:" + addr.getPort();
    Assert.assertEquals(expected, actual.get());
}
 
Example 3
Source File: UnixChannelUtil.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress computeRemoteAddr(InetSocketAddress remoteAddr, InetSocketAddress osRemoteAddr) {
    if (osRemoteAddr != null) {
        if (PlatformDependent.javaVersion() >= 7) {
            try {
                // Only try to construct a new InetSocketAddress if we using java >= 7 as getHostString() does not
                // exists in earlier releases and so the retrieval of the hostname could block the EventLoop if a
                // reverse lookup would be needed.
                return new InetSocketAddress(InetAddress.getByAddress(remoteAddr.getHostString(),
                        osRemoteAddr.getAddress().getAddress()),
                        osRemoteAddr.getPort());
            } catch (UnknownHostException ignore) {
                // Should never happen but fallback to osRemoteAddr anyway.
            }
        }
        return osRemoteAddr;
    }
    return remoteAddr;
}
 
Example 4
Source File: RpcContext.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
/**
 * is consumer side.
 *
 * @return consumer side.
 */
public boolean isConsumerSide() {
    URL url = getUrl();
    if (url == null) {
        return false;
    }
    InetSocketAddress address = getRemoteAddress();
    if (address == null) {
        return false;
    }
    String host;
    if (address.getAddress() == null) {
        host = address.getHostName();
    } else {
        host = address.getAddress().getHostAddress();
    }
    return url.getPort() == address.getPort() &&
            NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host));
}
 
Example 5
Source File: SctpChannelImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Binds the channel's socket to a local address.
 */
@Override
public SctpChannel bind(SocketAddress local) throws IOException {
    synchronized (receiveLock) {
        synchronized (sendLock) {
            synchronized (stateLock) {
                ensureOpenAndUnconnected();
                if (isBound())
                    SctpNet.throwAlreadyBoundException();
                InetSocketAddress isa = (local == null) ?
                    new InetSocketAddress(0) : Net.checkAddress(local);
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    sm.checkListen(isa.getPort());
                }
                Net.bind(fd, isa.getAddress(), isa.getPort());
                InetSocketAddress boundIsa = Net.localAddress(fd);
                port = boundIsa.getPort();
                localAddresses.add(isa);
                if (isa.getAddress().isAnyLocalAddress())
                    wildcard = true;
            }
        }
    }
    return this;
}
 
Example 6
Source File: Ping.java    From bt with Apache License 2.0 5 votes vote down vote up
@Override
protected void process() {
	InetAddress addr;
	int port;
	
	try {
		String ip = arguments.get(0);
		
		Matcher m = Pattern.compile("^(?:0x)?(\\p{XDigit}+)$").matcher(ip);
		
		if(m.matches()) {
			String hex = m.group(1);
			byte[] raw = hex2ary(hex);
			InetSocketAddress sockaddr = AddressUtils.unpackAddress(raw);
			addr = sockaddr.getAddress();
			port = sockaddr.getPort();
		} else {
			port = Integer.valueOf(arguments.get(1));
			addr = InetAddress.getByName(ip);
		}
		
	} catch (Exception e) {
		handleException(e);
		return;
	}
	
	target = new InetSocketAddress(addr, port);
	
	println("PING " + target);
	
	doPing();
}
 
Example 7
Source File: HostName.java    From IPAddress with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a host name from an InetSocketAddress.
 * 
 * @param inetSocketAddr
 */
public HostName(InetSocketAddress inetSocketAddr) {
	if(!inetSocketAddr.isUnresolved()) {
		resolvedAddress = toIPAddress(inetSocketAddr.getAddress(), IPAddressString.DEFAULT_VALIDATION_OPTIONS);
	}
	// we will parse and normalize as usual
	// there is no way to know if we are getting a host name string here or an ip address literal without parsing it ourselves
	host = inetSocketAddr.getHostString().trim() + PORT_SEPARATOR + inetSocketAddr.getPort();
	validationOptions = DEFAULT_VALIDATION_OPTIONS;
}
 
Example 8
Source File: HttpProxy.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void processRequest(Socket clientSocket) throws Exception {
    MessageHeader mheader = new MessageHeader(clientSocket.getInputStream());
    String statusLine = mheader.getValue(0);

    if (!statusLine.startsWith("CONNECT")) {
        out.println("proxy server: processes only "
                          + "CONNECT method requests, recieved: "
                          + statusLine);
        return;
    }

    // retrieve the host and port info from the status-line
    InetSocketAddress serverAddr = getConnectInfo(statusLine);

    //open socket to the server
    try (Socket serverSocket = new Socket(serverAddr.getAddress(),
                                          serverAddr.getPort())) {
        Forwarder clientFW = new Forwarder(clientSocket.getInputStream(),
                                           serverSocket.getOutputStream());
        Thread clientForwarderThread = new Thread(clientFW, "ClientForwarder");
        clientForwarderThread.start();
        send200(clientSocket);
        Forwarder serverFW = new Forwarder(serverSocket.getInputStream(),
                                           clientSocket.getOutputStream());
        serverFW.run();
        clientForwarderThread.join();
    }
}
 
Example 9
Source File: WebSocketHostAllowlistTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Before
public void initServerAndClient() {
  webSocketConfiguration.setPort(0);
  vertx = Vertx.vertx();

  final Map<String, JsonRpcMethod> websocketMethods =
      new WebSocketMethodsFactory(
              new SubscriptionManager(new NoOpMetricsSystem()), new HashMap<>())
          .methods();
  webSocketRequestHandlerSpy =
      spy(
          new WebSocketRequestHandler(
              vertx,
              websocketMethods,
              mock(EthScheduler.class),
              TimeoutOptions.defaultOptions().getTimeoutSeconds()));

  websocketService =
      new WebSocketService(vertx, webSocketConfiguration, webSocketRequestHandlerSpy);
  websocketService.start().join();
  final InetSocketAddress inetSocketAddress = websocketService.socketAddress();

  websocketPort = inetSocketAddress.getPort();
  final HttpClientOptions httpClientOptions =
      new HttpClientOptions()
          .setDefaultHost(webSocketConfiguration.getHost())
          .setDefaultPort(websocketPort);

  httpClient = vertx.createHttpClient(httpClientOptions);
}
 
Example 10
Source File: TimelineClientImpl.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void cancelDelegationToken(
    final Token<TimelineDelegationTokenIdentifier> timelineDT)
        throws IOException, YarnException {
  final boolean isTokenServiceAddrEmpty =
      timelineDT.getService().toString().isEmpty();
  final String scheme = isTokenServiceAddrEmpty ? null
      : (YarnConfiguration.useHttps(this.getConfig()) ? "https" : "http");
  final InetSocketAddress address = isTokenServiceAddrEmpty ? null
      : SecurityUtil.getTokenServiceAddr(timelineDT);
  PrivilegedExceptionAction<Void> cancelDTAction =
      new PrivilegedExceptionAction<Void>() {

        @Override
        public Void run() throws Exception {
          // If the timeline DT to cancel is different than cached, replace it.
          // Token to set every time for retry, because when exception happens,
          // DelegationTokenAuthenticatedURL will reset it to null;
          if (!timelineDT.equals(token.getDelegationToken())) {
            token.setDelegationToken((Token) timelineDT);
          }
          DelegationTokenAuthenticatedURL authUrl =
              new DelegationTokenAuthenticatedURL(authenticator,
                  connConfigurator);
          // If the token service address is not available, fall back to use
          // the configured service address.
          final URI serviceURI = isTokenServiceAddrEmpty ? resURI
              : new URI(scheme, null, address.getHostName(),
              address.getPort(), RESOURCE_URI_STR, null, null);
          authUrl.cancelDelegationToken(serviceURI.toURL(), token, doAsUser);
          return null;
        }
      };
  operateDelegationToken(cancelDTAction);
}
 
Example 11
Source File: NetStatusProtocolTester.java    From BiglyBT with GNU General Public License v2.0 5 votes vote down vote up
protected InetSocketAddress
adjustLoopback(
	InetSocketAddress	address )
{
	InetSocketAddress local = dht_plugin.getLocalAddress().getAddress();

	if ( local.getAddress().getHostAddress().equals( address.getAddress().getHostAddress())){

		return( new InetSocketAddress( "127.0.0.1", address.getPort()));

	}else{

		return( address );
	}
}
 
Example 12
Source File: NetworkBridge.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static int getSocketLocalPort(FileDescriptor fd) throws SocketException {
    try {
        SocketAddress sa = NetworkOs.getsockname(fd);
        InetSocketAddress isa = (InetSocketAddress) sa;
        return isa.getPort();
    } catch (ErrnoException errnoException) {
        throw new SocketException(errnoException.getMessage(), errnoException);
    }
}
 
Example 13
Source File: ChatTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static ChatServer startServer() throws IOException {
    ChatServer server = new ChatServer(0);
    InetSocketAddress address = (InetSocketAddress) server.getSocketAddress();
    listeningPort = address.getPort();
    server.run();
    return server;
}
 
Example 14
Source File: OPEN_CONNECTION_REPLY_2.java    From Nemisys with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void decode() {
    super.decode();
    this.offset += 16; //skip magic bytes
    this.serverID = this.getLong();
    InetSocketAddress address = this.getAddress();
    this.clientAddress = address.getHostString();
    this.clientPort = address.getPort();
    this.mtuSize = this.getSignedShort();
}
 
Example 15
Source File: DCCHistory.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
public Entry(DCCServerManager.UploadEntry upload, DCCServer.UploadSession session,
             DCCManager.UploadServerInfo server, Date date) {
    this.entryType = TYPE_UPLOAD;
    this.date = date;
    this.serverName = server.getServerName();
    this.serverUUID = server.getServerUUID();
    this.userNick = upload.getUser();
    InetSocketAddress addr = (InetSocketAddress) session.getRemoteAddress();
    this.remoteAddress = addr.getAddress().getHostAddress() + ":" + addr.getPort();
    this.fileName = upload.getFileName();
    this.fileSize = session.getAcknowledgedSize();
}
 
Example 16
Source File: TestTajoJdbc.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  tpch = TpchTestBase.getInstance();

  TajoConf tajoConf = tpch.getTestingCluster().getMaster().getContext().getConf();
  InetSocketAddress tajoMasterAddress =
      NetUtils.createSocketAddr(tajoConf.getVar(TajoConf.ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS));

  Class.forName("org.apache.tajo.jdbc.TajoDriver").newInstance();

  connUri = "jdbc:tajo://" + tajoMasterAddress.getHostName() + ":" + tajoMasterAddress.getPort();
  conn = DriverManager.getConnection(connUri);
}
 
Example 17
Source File: AtlasServerIdSelector.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Return the ID corresponding to this Atlas instance.
 *
 * The match is done by looking for an ID configured in {@link HAConfiguration#ATLAS_SERVER_IDS} key
 * that has a host:port entry for the key {@link HAConfiguration#ATLAS_SERVER_ADDRESS_PREFIX}+ID where
 * the host is a local IP address and port is set in the system property
 * {@link AtlasConstants#SYSTEM_PROPERTY_APP_PORT}.
 *
 * @param configuration
 * @return
 * @throws AtlasException if no ID is found that maps to a local IP Address or port
 */
public static String selectServerId(Configuration configuration) throws AtlasException {
    // ids are already trimmed by this method
    String[] ids = configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS);
    String matchingServerId = null;
    int appPort = Integer.parseInt(System.getProperty(AtlasConstants.SYSTEM_PROPERTY_APP_PORT));
    for (String id : ids) {
        String hostPort = configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +id);
        if (!StringUtils.isEmpty(hostPort)) {
            InetSocketAddress socketAddress;
            try {
                socketAddress = NetUtils.createSocketAddr(hostPort);
            } catch (Exception e) {
                LOG.warn("Exception while trying to get socket address for {}", hostPort, e);
                continue;
            }
            if (!socketAddress.isUnresolved()
                    && NetUtils.isLocalAddress(socketAddress.getAddress())
                    && appPort == socketAddress.getPort()) {
                LOG.info("Found matched server id {} with host port: {}", id, hostPort);
                matchingServerId = id;
                break;
            }
        } else {
            LOG.info("Could not find matching address entry for id: {}", id);
        }
    }
    if (matchingServerId == null) {
        String msg = String.format("Could not find server id for this instance. " +
                        "Unable to find IDs matching any local host and port binding among %s",
                StringUtils.join(ids, ","));
        throw new AtlasException(msg);
    }
    return matchingServerId;
}
 
Example 18
Source File: NetUtils.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
public static String toAddressString(InetSocketAddress address) {
    return address.getAddress().getHostAddress() + ":" + address.getPort();
}
 
Example 19
Source File: TajoAdmin.java    From tajo with Apache License 2.0 4 votes vote down vote up
public void runCommand(String[] args) throws Exception {
  CommandLineParser parser = new PosixParser();
  CommandLine cmd = parser.parse(options, args);

  String param = "";
  int cmdType = 0;

  String hostName = null;
  Integer port = null;
  if (cmd.hasOption("h")) {
    hostName = cmd.getOptionValue("h");
  }
  if (cmd.hasOption("p")) {
    port = Integer.parseInt(cmd.getOptionValue("p"));
  }

  String queryId = null;

  if (cmd.hasOption("list")) {
    cmdType = 1;
  } else if (cmd.hasOption("desc")) {
    cmdType = 2;
  } else if (cmd.hasOption("cluster")) {
    cmdType = 3;
  } else if (cmd.hasOption("kill")) {
    cmdType = 4;
    queryId = cmd.getOptionValue("kill");
  } else if (cmd.hasOption("showmasters")) {
    cmdType = 5;
  }

  // if there is no "-h" option,
  InetSocketAddress address = tajoConf.getSocketAddrVar(TajoConf.ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS,
      TajoConf.ConfVars.TAJO_MASTER_UMBILICAL_RPC_ADDRESS);

  if(hostName == null) {
    hostName = address.getHostName();
  }

  if (port == null) {
    port = address.getPort();
  }

  if (cmdType == 0) {
    printUsage();
    return;
  }


  if ((hostName == null) ^ (port == null)) {
    System.err.println("ERROR: cannot find valid Tajo server address");
    return;
  } else if (hostName != null && port != null) {
    tajoConf.setVar(TajoConf.ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS, NetUtils.getHostPortString(hostName, port));
    tajoClient = new TajoClientImpl(ServiceTrackerFactory.get(tajoConf));
  } else if (hostName == null && port == null) {
    tajoClient = new TajoClientImpl(ServiceTrackerFactory.get(tajoConf));
  }

  switch (cmdType) {
    case 1:
      processList(writer);
      break;
    case 2:
      processDesc(writer);
      break;
    case 3:
      processCluster(writer);
      break;
    case 4:
      processKill(writer, queryId);
      break;
    case 5:
      processMasters(writer);
      break;
    default:
      printUsage();
      break;
  }

  writer.flush();
}
 
Example 20
Source File: NetWorkUtil.java    From dts with Apache License 2.0 4 votes vote down vote up
public static String toStringAddress(InetSocketAddress address) {
    return address.getAddress().getHostAddress() + ":" + address.getPort();
}