当前位置: 首页>>代码示例>>Java>>正文


Java InetSocketAddress.getHostName方法代码示例

本文整理汇总了Java中java.net.InetSocketAddress.getHostName方法的典型用法代码示例。如果您正苦于以下问题:Java InetSocketAddress.getHostName方法的具体用法?Java InetSocketAddress.getHostName怎么用?Java InetSocketAddress.getHostName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.InetSocketAddress的用法示例。


在下文中一共展示了InetSocketAddress.getHostName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: cancelDelegationToken

import java.net.InetSocketAddress; //导入方法依赖的package包/类
@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);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:37,代码来源:TimelineClientImpl.java

示例2: resetNextInetSocketAddress

import java.net.InetSocketAddress; //导入方法依赖的package包/类
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
  socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

  String socketHost;
  if (proxy.type() == Proxy.Type.DIRECT) {
    socketHost = uri.getHost();
    socketPort = getEffectivePort(uri);
  } else {
    SocketAddress proxyAddress = proxy.address();
    if (!(proxyAddress instanceof InetSocketAddress)) {
      throw new IllegalArgumentException(
          "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
    }
    InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
    socketHost = proxySocketAddress.getHostName();
    socketPort = proxySocketAddress.getPort();
  }

  // Try each address for best behavior in mixed IPv4/IPv6 environments.
  socketAddresses = dns.getAllByName(socketHost);
  nextSocketAddressIndex = 0;
}
 
开发者ID:aabognah,项目名称:LoRaWAN-Smart-Parking,代码行数:24,代码来源:RouteSelector.java

示例3: getAddressListFromTool

import java.net.InetSocketAddress; //导入方法依赖的package包/类
/**
 * Using {@link GetConf} methods get the list of given {@code type} of
 * addresses
 * 
 * @param type, TestType
 * @param conf, configuration
 * @param checkPort, If checkPort is true, verify NNPRCADDRESSES whose 
 *      expected value is hostname:rpc-port.  If checkPort is false, the 
 *      expected is hostname only.
 * @param expected, expected addresses
 */
private void getAddressListFromTool(TestType type, HdfsConfiguration conf,
    boolean checkPort, List<ConfiguredNNAddress> expected) throws Exception {
  String out = getAddressListFromTool(type, conf, expected.size() != 0);
  List<String> values = new ArrayList<String>();
  
  // Convert list of addresses returned to an array of string
  StringTokenizer tokenizer = new StringTokenizer(out);
  while (tokenizer.hasMoreTokens()) {
    String s = tokenizer.nextToken().trim();
    values.add(s);
  }
  String[] actual = values.toArray(new String[values.size()]);

  // Convert expected list to String[] of hosts
  int i = 0;
  String[] expectedHosts = new String[expected.size()];
  for (ConfiguredNNAddress cnn : expected) {
    InetSocketAddress addr = cnn.getAddress();
    if (!checkPort) {
      expectedHosts[i++] = addr.getHostName();
    }else {
      expectedHosts[i++] = addr.getHostName()+":"+addr.getPort();
    }
  }

  // Compare two arrays
  assertTrue(Arrays.equals(expectedHosts, actual));
}
 
开发者ID:naver,项目名称:hadoop,代码行数:40,代码来源:TestGetConf.java

示例4: connectSocket

import java.net.InetSocketAddress; //导入方法依赖的package包/类
public Socket connectSocket(
        final Socket sock,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    final String host = remoteAddress.getHostName();
    final int port = remoteAddress.getPort();
    InetAddress local = null;
    int localPort = 0;
    if (localAddress != null) {
        local = localAddress.getAddress();
        localPort = localAddress.getPort();
    }
    return this.factory.connectSocket(sock, host, port, local, localPort, params);
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:16,代码来源:SchemeSocketFactoryAdaptor.java

示例5: makeQueryGetter

import java.net.InetSocketAddress; //导入方法依赖的package包/类
public void makeQueryGetter()
{
    try
    {
        if (FMLClientHandler.instance().getClientToServerNetworkManager() != null)
        {
            SocketAddress socketAddress = FMLClientHandler.instance().getClientToServerNetworkManager().getRemoteAddress();

            String host = "127.0.0.1";
            int port = 25565;

            if (socketAddress instanceof InetSocketAddress)
            {
                InetSocketAddress add = (InetSocketAddress) socketAddress;
                host = add.getHostName();
                port = add.getPort();
            }

            queryGetter = new QueryGetter(host, port);
        }
    }
    catch (Throwable t)
    {
        // Catch _ALL_ errors. We should _NEVER_ crash.
    }

}
 
开发者ID:CreeperHost,项目名称:CreeperHostGui,代码行数:28,代码来源:CreeperHost.java

示例6: getPermission

import java.net.InetSocketAddress; //导入方法依赖的package包/类
@Override public Permission getPermission() throws IOException {
  URL url = getURL();
  String hostname = url.getHost();
  int hostPort = url.getPort() != -1
      ? url.getPort()
      : HttpUrl.defaultPort(url.getProtocol());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) client.proxy().address();
    hostname = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostname + ":" + hostPort, "connect, resolve");
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:14,代码来源:OkHttpURLConnection.java

示例7: getResolvedMRHistoryWebAppURLWithoutScheme

import java.net.InetSocketAddress; //导入方法依赖的package包/类
public static String getResolvedMRHistoryWebAppURLWithoutScheme(
    Configuration conf, boolean isSSLEnabled) {
  InetSocketAddress address = null;
  if (isSSLEnabled) {
    address =
        conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
            JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
            JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_PORT);
  } else {
    address =
        conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS,
            JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_ADDRESS,
            JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_PORT);    }
  address = NetUtils.getConnectAddress(address);
  StringBuffer sb = new StringBuffer();
  InetAddress resolved = address.getAddress();
  if (resolved == null || resolved.isAnyLocalAddress() || 
      resolved.isLoopbackAddress()) {
    String lh = address.getHostName();
    try {
      lh = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
      //Ignore and fallback.
    }
    sb.append(lh);
  } else {
    sb.append(address.getHostName());
  }
  sb.append(":").append(address.getPort());
  return sb.toString();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:32,代码来源:MiniMRYarnCluster.java

示例8: MyProxy

import java.net.InetSocketAddress; //导入方法依赖的package包/类
public MyProxy(Proxy proxy) {
    type = type2Type.get(proxy.type());
    
    final InetSocketAddress address = (InetSocketAddress) proxy.address();
    if (address != null) {
        host = address.getHostName();
        port = address.getPort();
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:10,代码来源:MyProxy.java

示例9: getExchangeChannel

import java.net.InetSocketAddress; //导入方法依赖的package包/类
@Override
public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) {
    String host = remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : remoteAddress.getHostName();
    int port = remoteAddress.getPort();
    ExchangeChannel channel = super.getExchangeChannel(remoteAddress);
    if (channel == null) {
        for (Map.Entry<URL, ExchangeClient> entry : clients.entrySet()) {
            URL url = entry.getKey();
            if (url.getIp().equals(host) && url.getPort() == port) {
                return entry.getValue();
            }
        }
    }
    return channel;
}
 
开发者ID:zhuxiaolei,项目名称:dubbo2,代码行数:16,代码来源:ExchangeServerPeer.java

示例10: testLiteralIPNoReverseNS

import java.net.InetSocketAddress; //导入方法依赖的package包/类
@Test
public void testLiteralIPNoReverseNS() throws Exception {
    byte size = 30;
    HostProvider hostProvider = getHostProviderUnresolved(size);
    for (int i = 0; i < size; i++) {
        InetSocketAddress next = hostProvider.next(0);
        assertTrue(next instanceof InetSocketAddress);
        assertTrue(!next.isUnresolved());
        assertTrue("Did not match "+ next.toString(), !next.toString().startsWith("/"));
        // Do NOT trigger the reverse name service lookup.
        String hostname = next.getHostName();
        // In this case, the hostname equals literal IP address.
        hostname.equals(next.getAddress().getHostAddress());
    }
}
 
开发者ID:l294265421,项目名称:ZooKeeper,代码行数:16,代码来源:StaticHostProviderTest.java

示例11: checkTableInfo

import java.net.InetSocketAddress; //导入方法依赖的package包/类
void checkTableInfo(TableInfoModel model) {
  assertEquals(model.getName(), TABLE.getNameAsString());
  Iterator<TableRegionModel> regions = model.getRegions().iterator();
  assertTrue(regions.hasNext());
  while (regions.hasNext()) {
    TableRegionModel region = regions.next();
    boolean found = false;
    for (HRegionLocation e: regionMap) {
      HRegionInfo hri = e.getRegionInfo();
      String hriRegionName = hri.getRegionNameAsString();
      String regionName = region.getName();
      if (hriRegionName.equals(regionName)) {
        found = true;
        byte[] startKey = hri.getStartKey();
        byte[] endKey = hri.getEndKey();
        ServerName serverName = e.getServerName();
        InetSocketAddress sa =
            new InetSocketAddress(serverName.getHostname(), serverName.getPort());
        String location = sa.getHostName() + ":" +
          Integer.valueOf(sa.getPort());
        assertEquals(hri.getRegionId(), region.getId());
        assertTrue(Bytes.equals(startKey, region.getStartKey()));
        assertTrue(Bytes.equals(endKey, region.getEndKey()));
        assertEquals(location, region.getLocation());
        break;
      }
    }
    assertTrue(found);
  }
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:31,代码来源:TestTableResource.java

示例12: initChannel

import java.net.InetSocketAddress; //导入方法依赖的package包/类
@Override
protected void initChannel(Channel channel) throws Exception {
    InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
    Address clientAddress = new Address(address.getHostName(), address.getPort());
    channel.pipeline().addLast(
            master.proxyHandler(clientAddress),
            new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
                        throws Exception {
                    LOGGER.info("[Client ({})] => Unhandled inbound: {}", clientAddress, o);
                }
            });
}
 
开发者ID:chhsiao90,项目名称:nitmproxy,代码行数:15,代码来源:NitmProxyInitializer.java

示例13: startConnect

import java.net.InetSocketAddress; //导入方法依赖的package包/类
private void startConnect() throws IOException {
    state = States.CONNECTING;

    InetSocketAddress addr;
    if (rwServerAddress != null) {
        addr = rwServerAddress;
        rwServerAddress = null;
    } else {
        addr = hostProvider.next(1000);
    }

    setName(getName().replaceAll("\\(.*\\)",
            "(" + addr.getHostName() + ":" + addr.getPort() + ")"));
    if (ZooKeeperSaslClient.isEnabled()) {
        try {
            String principalUserName = System.getProperty(
                    ZK_SASL_CLIENT_USERNAME, "zookeeper");
            zooKeeperSaslClient =
                new ZooKeeperSaslClient(
                        principalUserName+"/"+addr.getHostName());
        } catch (LoginException e) {
            // An authentication error occurred when the SASL client tried to initialize:
            // for Kerberos this means that the client failed to authenticate with the KDC.
            // This is different from an authentication error that occurs during communication
            // with the Zookeeper server, which is handled below.
            LOG.warn("SASL configuration failed: " + e + " Will continue connection to Zookeeper server without "
              + "SASL authentication, if Zookeeper server allows it.");
            eventThread.queueEvent(new WatchedEvent(
              Watcher.Event.EventType.None,
              Watcher.Event.KeeperState.AuthFailed, null));
            saslLoginFailed = true;
        }
    }
    logStartConnect(addr);

    clientCnxnSocket.connect(addr);
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:38,代码来源:ClientCnxn.java

示例14: getRemoteIp

import java.net.InetSocketAddress; //导入方法依赖的package包/类
public static String getRemoteIp(Channel channel) {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
    if (inetSocketAddress == null) {
        return "";
    }
    final InetAddress inetAddr = inetSocketAddress.getAddress();
    return inetAddr != null ? inetAddr.getHostAddress() : inetSocketAddress.getHostName();
}
 
开发者ID:lirenzuo,项目名称:rocketmq-rocketmq-all-4.1.0-incubating,代码行数:9,代码来源:ChannelUtil.java

示例15: testCnxFromFutureVersion

import java.net.InetSocketAddress; //导入方法依赖的package包/类
/**
 * Before 3.5.0 a server sends its id when connecting to another server.
 * Starting with 3.5.0 a server will send a protocol version, followed by
 * its id, then number of bytes in the remainder of the message and finally
 * the rest of the message. The test makes sure that a 3.4.6 server is able
 * to detect that a connection message has this new format, extract the id,
 * and skip the remainder of the message. 
 * 
 * {@link https://issues.apache.org/jira/browse/ZOOKEEPER-1633}
 * 
 * @throws Exception
 */
@Test
public void testCnxFromFutureVersion() throws Exception {               
    QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2);
    TestCnxManager cnxManager = new TestCnxManager(peer);
    QuorumCnxManager.Listener listener = cnxManager.listener;
    if(listener != null){
        listener.start();
    } else {
        Assert.fail("Null listener when initializing cnx manager");
    }
    
    int port = peers.get(peer.getId()).electionAddr.getPort();
    LOG.info("Election port: " + port);
    
    Thread.sleep(1000);
    
    SocketChannel sc = SocketChannel.open();
    sc.socket().connect(peers.get(new Long(1)).electionAddr, 5000);
    
    InetSocketAddress otherAddr = peers.get(new Long(2)).electionAddr;
    DataOutputStream dout = new DataOutputStream(sc.socket().getOutputStream());
    // protocol version - a negative number
    dout.writeLong(0xffff0000);
    // server id
    dout.writeLong(new Long(2));
    // other stuff that a 3.5.0 server will send - not important for 3.4.6
    // the 3.4.6 server should just skip it
    String addr = otherAddr.getHostName()+ ":" + otherAddr.getPort();
    byte[] addr_bytes = addr.getBytes();
    dout.writeInt(addr_bytes.length);
    dout.write(addr_bytes);
    dout.flush();
    
    Thread.sleep(1000);
    
    Assert.assertEquals("Server 1 got connection request from server 2", 
            true, cnxManager.senderWorkerMapContains(new Long(2)));
  
    // send another message to make sure the connection message was processed
    // properly (mainly that its suffix was removed from the stream)
    String testStr = "this is a test message string";
    byte[] testStr_bytes = testStr.getBytes();
    dout.writeInt(testStr_bytes.length);
    dout.write(testStr_bytes);
    dout.flush();
    
    Message m = null;
    int numRetries = 1;
    while((m == null) && (numRetries++ <= THRESHOLD)){
        m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
        if(m == null) cnxManager.connectAll();
    }

    if(numRetries > THRESHOLD){
        Assert.fail("Test message hasn't been found in recvQueue");
    }

    //Assert.assertEquals("Message sender should be 2", 2, m.sid);
    Assert.assertEquals("Message sender should be 2", 2, cnxManager.getSid(m));
    Assert.assertEquals("Message from 2 doesn't match test sring", testStr, 
            cnxManager.getMsgString(m));
  
    peer.shutdown();
    cnxManager.halt();
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:78,代码来源:CnxManagerTest.java


注:本文中的java.net.InetSocketAddress.getHostName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。