java.net.InetAddress#getHostAddress ( )源码实例Demo

下面列出了java.net.InetAddress#getHostAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: HttpInfo   文件: Dns.java
private static String[] readDnsServersFromSystemProperties() {
    SystemProperties.init();
    LinkedList<String> dnsServers = new LinkedList<>();
    for (String property : DNS_SERVER_PROPERTIES) {
        String server = SystemProperties.get(property, "");
        if (server != null && !server.isEmpty()) {
            try {
                InetAddress ip = InetAddress.getByName(server);
                if (ip == null) {
                    continue;
                }
                server = ip.getHostAddress();
                if (server == null || server.isEmpty()) {
                    continue;
                }
            } catch (Throwable throwable) {
                continue;
            }
            dnsServers.add(server);
        }
    }
    return dnsServers.toArray(new String[dnsServers.size()]);
}
 
源代码2 项目: onpc   文件: BroadcastResponseMsg.java
public BroadcastResponseMsg(InetAddress hostAddress, EISCPMessage raw) throws Exception
{
    super(raw);
    host = hostAddress.getHostAddress();
    String[] tokens = data.split("/");
    if (tokens.length > 0)
    {
        model = tokens[0];
    }
    if (tokens.length > 1)
    {
        port = Integer.parseInt(tokens[1], 10);
    }
    if (tokens.length > 2)
    {
        destinationArea = tokens[2];
    }
    if (tokens.length > 3)
    {
        identifier = tokens[3];
    }
}
 
源代码3 项目: Quicksql   文件: JdbcServer.java
public static void main(String[] args) throws Exception {
    OptionsParser parser = new OptionsParser(args);
    final int port = Integer.parseInt(parser.getOptionValue(SubmitOption.PORT));
    final String[] mainArgs = new String[]{FullyRemoteJdbcMetaFactory.class.getName()};

    HttpServer server = Main.start(mainArgs, port, new HandlerFactory() {
        @Override
        public AbstractHandler createHandler(Service service) {
            return new AvaticaJsonHandler(service);
        }
    });
    InetAddress address = InetAddress.getLocalHost();
    String hostName = "localhost";
    if (address != null) {
         hostName = StringUtils.isNotBlank(address.getHostName()) ? address.getHostName() : address
            .getHostAddress();
    }
    String url = Driver.CONNECT_STRING_PREFIX + "url=http://" + hostName + ":" + server.getPort();
    System.out.println("Quicksql server started, Please connect : " + url);
    server.join();
}
 
源代码4 项目: zooadmin   文件: BaseTool.java
public static String getServer() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ArrayList<String> endPoints = new ArrayList<String>();
    try {
        Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);
        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext(); ) {
            ObjectName obj = i.next();
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            for (InetAddress addr : addresses) {
                String host = addr.getHostAddress();
                String ep = scheme + "://" + host + ":" + port;
                endPoints.add(ep);
            }
        }
    } catch (Exception e) {
        return "";
    }
    if (endPoints.size() > 0) {
        return endPoints.get(0);
    } else {
        return "";
    }
}
 
源代码5 项目: rocketmq   文件: MessageExt.java
public String getBornHostString() {
    if (null != this.bornHost) {
        InetAddress inetAddress = ((InetSocketAddress) this.bornHost).getAddress();

        return null != inetAddress ? inetAddress.getHostAddress() : null;
    }

    return null;
}
 
源代码6 项目: kob   文件: IpUtils.java
private static boolean isValidAddress(InetAddress address) {
    if (address == null || address.isLoopbackAddress()) {
        return false;
    }
    String name = address.getHostAddress();
    return (name != null
            && !ANY_HOST.equals(name)
            && !LOCALHOST.equals(name)
            && IP_PATTERN.matcher(name).matches());
}
 
源代码7 项目: Jupiter   文件: NetUtil.java
private static boolean isValidAddress(InetAddress address) {
    if (address.isLoopbackAddress()) {
        return false;
    }

    String name = address.getHostAddress();
    return (name != null
            && !"0.0.0.0".equals(name)
            && !"127.0.0.1".equals(name)
            && IP_PATTERN.matcher(name).matches());
}
 
源代码8 项目: ats-framework   文件: HostUtils.java
/**
 * Get the IP (not the loopback 127.0.0.1) of the local host. Note: it will
 * return the first valid one, so the result is not clear when have more
 * than one network card installed.
 * @param excludeDownOnes - whether to exclude interfaces that are down
 * @return
 */
public static String getLocalHostIP( boolean excludeDownOnes ) {

    String localHostIP = "";
    InetAddress inetAddress = null;
    List<InetAddress> ipList = getIpAddressesList(true, excludeDownOnes);
    if (ipList.size() > 0) {
        inetAddress = ipList.get(0);
    }
    if (inetAddress != null) {
        localHostIP = inetAddress.getHostAddress();
    }
    return localHostIP;
}
 
源代码9 项目: scipio-erp   文件: NetConverters.java
public String convert(InetAddress obj) throws ConversionException {
    String hostName = obj.getHostName();
    if (hostName != null) {
        return hostName;
    }
    return obj.getHostAddress();
}
 
源代码10 项目: incubator-tez   文件: MRHelpers.java
/**
 * Sets up parameters which used to be set by the MR JobClient. Includes
 * setting whether to use the new api or the old api. Note: Must be called
 * before generating InputSplits
 *
 * @param conf
 *          configuration for the vertex.
 */
public static void doJobClientMagic(Configuration conf) throws IOException {
  setUseNewAPI(conf);
  // TODO Maybe add functionality to check output specifications - e.g. fail
  // early if the output directory exists.
  InetAddress ip = InetAddress.getLocalHost();
  if (ip != null) {
    String submitHostAddress = ip.getHostAddress();
    String submitHostName = ip.getHostName();
    conf.set(MRJobConfig.JOB_SUBMITHOST, submitHostName);
    conf.set(MRJobConfig.JOB_SUBMITHOSTADDR, submitHostAddress);
  }
  // conf.set("hadoop.http.filter.initializers",
  // "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer");
  // Skipping setting JOB_DIR - not used by AM.

  // Maybe generate SHUFFLE secret. The AM uses the job token generated in
  // the AM anyway.

  // TODO eventually ACLs
  conf.set(TezJobConfig.TEZ_RUNTIME_PARTITIONER_CLASS, MRPartitioner.class.getName());
  
  boolean useNewApi = conf.getBoolean("mapred.mapper.new-api", false);
  if (useNewApi) {
    if (conf.get(MRJobConfig.COMBINE_CLASS_ATTR) != null) {
      conf.set(TezJobConfig.TEZ_RUNTIME_COMBINER_CLASS, MRCombiner.class.getName());
    }
  } else {
    if (conf.get("mapred.combiner.class") != null) {
      conf.set(TezJobConfig.TEZ_RUNTIME_COMBINER_CLASS, MRCombiner.class.getName());
    }
  }
  
  setWorkingDirectory(conf);
}
 
源代码11 项目: linstor-server   文件: BaseErrorReporter.java
void reportPeer(PrintStream output, Peer client)
{
    String peerAddress = null;
    int peerPort = 0;

    String peerId = client.toString();
    InetSocketAddress socketAddr = client.peerAddress();
    if (socketAddr != null)
    {
        InetAddress ipAddr = socketAddr.getAddress();
        peerPort = socketAddr.getPort();
        if (ipAddr != null)
        {
            peerAddress = ipAddr.getHostAddress();
        }
    }

    if (peerId != null)
    {
        output.println("Connected peer information\n");
        output.printf(ERROR_FIELD_FORMAT, "Peer ID:", peerId);
        if (peerAddress == null)
        {
            output.println("The peer's network address is unknown.");
        }
        else
        {
            output.printf(ERROR_FIELD_FORMAT, "Network address:", peerAddress);
        }
    }
}
 
源代码12 项目: openjdk-8-source   文件: TCPEndpoint.java
/**
 * Do our best to obtain a fully qualified hostname for the local
 * host.  Perform the following steps to get a localhostname:
 *
 * 1. InetAddress.getLocalHost().getHostName() - if contains
 *    '.' use as FQDN
 * 2. if no '.' query name service for FQDN in a thread
 *    Note: We query the name service for an FQDN by creating
 *    an InetAddress via a stringified copy of the local ip
 *    address; this creates an InetAddress with a null hostname.
 *    Asking for the hostname of this InetAddress causes a name
 *    service lookup.
 *
 * 3. if name service takes too long to return, use ip address
 * 4. if name service returns but response contains no '.'
 *    default to ipaddress.
 */
static String attemptFQDN(InetAddress localAddr)
    throws java.net.UnknownHostException
{

    String hostName = localAddr.getHostName();

    if (hostName.indexOf('.') < 0 ) {

        String hostAddress = localAddr.getHostAddress();
        FQDN f = new FQDN(hostAddress);

        int nameServiceTimeOut =
            TCPEndpoint.getInt("sun.rmi.transport.tcp.localHostNameTimeOut",
                               10000);

        try {
            synchronized(f) {
                f.getFQDN();

                /* wait to obtain an FQDN */
                f.wait(nameServiceTimeOut);
            }
        } catch (InterruptedException e) {
            /* propagate the exception to the caller */
            Thread.currentThread().interrupt();
        }
        hostName = f.getHost();

        if ((hostName == null) || (hostName.equals(""))
            || (hostName.indexOf('.') < 0 )) {

            hostName = hostAddress;
        }
    }
    return hostName;
}
 
源代码13 项目: PowerFileExplorer   文件: FTPServerFragment.java
/**
  * @return address at which server is running
  */
 private String getFTPAddressString() {
     InetAddress ia = FTPService.getLocalInetAddress(getContext());
     if (ia == null) {
         throw new NullPointerException("getLocalInetAddress returned a null value");
     }
     return (getSecurePreference() ? FTPService.INITIALS_HOST_SFTP : FTPService.INITIALS_HOST_FTP)
+ ia.getHostAddress()  + ":" + getDefaultPortFromPreferences();
 }
 
源代码14 项目: Bytecoder   文件: SSLSocketImpl.java
private void useImplicitHost(boolean useNameService) {
    // Note: If the local name service is not trustworthy, reverse
    // host name resolution should not be performed for endpoint
    // identification.  Use the application original specified
    // hostname or IP address instead.

    // Get the original hostname via jdk.internal.access.SharedSecrets
    InetAddress inetAddress = getInetAddress();
    if (inetAddress == null) {      // not connected
        return;
    }

    JavaNetInetAddressAccess jna =
            SharedSecrets.getJavaNetInetAddressAccess();
    String originalHostname = jna.getOriginalHostName(inetAddress);
    if (originalHostname != null && !originalHostname.isEmpty()) {

        this.peerHost = originalHostname;
        if (conContext.sslConfig.serverNames.isEmpty() &&
                !conContext.sslConfig.noSniExtension) {
            conContext.sslConfig.serverNames =
                    Utilities.addToSNIServerNameList(
                            conContext.sslConfig.serverNames, peerHost);
        }

        return;
    }

    // No explicitly specified hostname, no server name indication.
    if (!useNameService) {
        // The local name service is not trustworthy, use IP address.
        this.peerHost = inetAddress.getHostAddress();
    } else {
        // Use the underlying reverse host name resolution service.
        this.peerHost = getInetAddress().getHostName();
    }
}
 
源代码15 项目: pentaho-kettle   文件: SlaveServer.java
public int allocateServerSocket( String runId, int portRangeStart, String hostname,
                                 String transformationName, String sourceSlaveName,
                                 String sourceStepName, String sourceStepCopy,
                                 String targetSlaveName, String targetStepName, String targetStepCopy )
  throws Exception {

  // Look up the IP address of the given hostname
  // Only this way we'll be to allocate on the correct host.
  //
  InetAddress inetAddress = InetAddress.getByName( hostname );
  String address = inetAddress.getHostAddress();

  String service = AllocateServerSocketServlet.CONTEXT_PATH + "/?";
  service += AllocateServerSocketServlet.PARAM_RANGE_START + "=" + Integer.toString( portRangeStart );
  service += "&" + AllocateServerSocketServlet.PARAM_ID + "=" + URLEncoder.encode( runId, "UTF-8" );
  service += "&" + AllocateServerSocketServlet.PARAM_HOSTNAME + "=" + address;
  service +=
    "&" + AllocateServerSocketServlet.PARAM_TRANSFORMATION_NAME + "="
      + URLEncoder.encode( transformationName, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_SOURCE_SLAVE + "=" + URLEncoder.encode( sourceSlaveName, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_SOURCE_STEPNAME + "=" + URLEncoder.encode( sourceStepName, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_SOURCE_STEPCOPY + "=" + URLEncoder.encode( sourceStepCopy, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_TARGET_SLAVE + "=" + URLEncoder.encode( targetSlaveName, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_TARGET_STEPNAME + "=" + URLEncoder.encode( targetStepName, "UTF-8" );
  service +=
    "&" + AllocateServerSocketServlet.PARAM_TARGET_STEPCOPY + "=" + URLEncoder.encode( targetStepCopy, "UTF-8" );
  service += "&xml=Y";
  String xml = execService( service );
  Document doc = XMLHandler.loadXMLString( xml );
  String portString = XMLHandler.getTagValue( doc, AllocateServerSocketServlet.XML_TAG_PORT );

  int port = Const.toInt( portString, -1 );
  if ( port < 0 ) {
    throw new Exception( "Unable to retrieve port from service : " + service + ", received : \n" + xml );
  }

  return port;
}
 
源代码16 项目: saluki   文件: NetUtils.java
public static String getLogHost() {
  InetAddress address = LOCAL_ADDRESS;
  return address == null ? LOCALHOST : address.getHostAddress();
}
 
源代码17 项目: wildfly-core   文件: OutboundSocketBinding.java
/**
 * Creates an outbound socket binding.
 *
 * @param name                   Name of the outbound socket binding
 * @param socketBindingManager   The socket binding manager
 * @param destinationAddress     The destination address to which this socket will be "connected". Cannot be null.
 * @param destinationPort        The destination port. Cannot be < 0.
 * @param sourceNetworkInterface (Optional) source network interface which will be used as the "source" of the socket binding
 * @param sourcePort             (Optional) source port. Cannot be null or < 0
 * @param fixedSourcePort        True if the <code>sourcePort</code> has to be used as a fixed port number. False if the <code>sourcePort</code>
 *                               will be added to the port offset while determining the absolute source port.
 */
public OutboundSocketBinding(final String name, final SocketBindingManager socketBindingManager,
                             final InetAddress destinationAddress, final int destinationPort,
                             final NetworkInterfaceBinding sourceNetworkInterface, final Integer sourcePort,
                             final boolean fixedSourcePort) {
    this(name, socketBindingManager, destinationAddress.getHostAddress(), destinationPort, sourceNetworkInterface, sourcePort, fixedSourcePort);
    this.resolvedDestinationAddress = destinationAddress;
}
 
源代码18 项目: jdk8u-dev-jdk   文件: SecurityManager.java
/**
 * Throws a <code>SecurityException</code> if the
 * calling thread is not allowed to use
 * (join/leave/send/receive) IP multicast.
 * <p>
 * This method calls <code>checkPermission</code> with the
 * <code>java.net.SocketPermission(maddr.getHostAddress(),
 * "accept,connect")</code> permission.
 * <p>
 * If you override this method, then you should make a call to
 * <code>super.checkMulticast</code>
 * at the point the overridden method would normally throw an
 * exception.
 *
 * @param      maddr  Internet group address to be used.
 * @exception  SecurityException  if the calling thread is not allowed to
 *  use (join/leave/send/receive) IP multicast.
 * @exception  NullPointerException if the address argument is
 *             <code>null</code>.
 * @since      JDK1.1
 * @see        #checkPermission(java.security.Permission) checkPermission
 */
public void checkMulticast(InetAddress maddr) {
    String host = maddr.getHostAddress();
    if (!host.startsWith("[") && host.indexOf(':') != -1) {
        host = "[" + host + "]";
    }
    checkPermission(new SocketPermission(host,
        SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
}
 
源代码19 项目: hottub   文件: SecurityManager.java
/**
 * Throws a <code>SecurityException</code> if the
 * calling thread is not allowed to use
 * (join/leave/send/receive) IP multicast.
 * <p>
 * This method calls <code>checkPermission</code> with the
 * <code>java.net.SocketPermission(maddr.getHostAddress(),
 * "accept,connect")</code> permission.
 * <p>
 * If you override this method, then you should make a call to
 * <code>super.checkMulticast</code>
 * at the point the overridden method would normally throw an
 * exception.
 *
 * @param      maddr  Internet group address to be used.
 * @param      ttl        value in use, if it is multicast send.
 * Note: this particular implementation does not use the ttl
 * parameter.
 * @exception  SecurityException  if the calling thread is not allowed to
 *  use (join/leave/send/receive) IP multicast.
 * @exception  NullPointerException if the address argument is
 *             <code>null</code>.
 * @since      JDK1.1
 * @deprecated Use #checkPermission(java.security.Permission) instead
 * @see        #checkPermission(java.security.Permission) checkPermission
 */
@Deprecated
public void checkMulticast(InetAddress maddr, byte ttl) {
    String host = maddr.getHostAddress();
    if (!host.startsWith("[") && host.indexOf(':') != -1) {
        host = "[" + host + "]";
    }
    checkPermission(new SocketPermission(host,
        SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
}
 
源代码20 项目: jdk1.8-source-analysis   文件: SecurityManager.java
/**
 * Throws a <code>SecurityException</code> if the
 * calling thread is not allowed to use
 * (join/leave/send/receive) IP multicast.
 * <p>
 * This method calls <code>checkPermission</code> with the
 * <code>java.net.SocketPermission(maddr.getHostAddress(),
 * "accept,connect")</code> permission.
 * <p>
 * If you override this method, then you should make a call to
 * <code>super.checkMulticast</code>
 * at the point the overridden method would normally throw an
 * exception.
 *
 * @param      maddr  Internet group address to be used.
 * @exception  SecurityException  if the calling thread is not allowed to
 *  use (join/leave/send/receive) IP multicast.
 * @exception  NullPointerException if the address argument is
 *             <code>null</code>.
 * @since      JDK1.1
 * @see        #checkPermission(java.security.Permission) checkPermission
 */
public void checkMulticast(InetAddress maddr) {
    String host = maddr.getHostAddress();
    if (!host.startsWith("[") && host.indexOf(':') != -1) {
        host = "[" + host + "]";
    }
    checkPermission(new SocketPermission(host,
        SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION));
}