Java Code Examples for java.net.InetAddress#getHostAddress()

The following examples show how to use java.net.InetAddress#getHostAddress() . 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: BaseTool.java    From zooadmin with MIT License 6 votes vote down vote up
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 "";
    }
}
 
Example 2
Source File: Dns.java    From HttpInfo with Apache License 2.0 6 votes vote down vote up
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()]);
}
 
Example 3
Source File: JdbcServer.java    From Quicksql with MIT License 6 votes vote down vote up
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();
}
 
Example 4
Source File: BroadcastResponseMsg.java    From onpc with GNU General Public License v3.0 6 votes vote down vote up
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];
    }
}
 
Example 5
Source File: MRHelpers.java    From incubator-tez with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 6
Source File: SSLSocketImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 7
Source File: FTPServerFragment.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
  * @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();
 }
 
Example 8
Source File: TCPEndpoint.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
Source File: BaseErrorReporter.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 10
Source File: NetConverters.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String convert(InetAddress obj) throws ConversionException {
    String hostName = obj.getHostName();
    if (hostName != null) {
        return hostName;
    }
    return obj.getHostAddress();
}
 
Example 11
Source File: HostUtils.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: NetUtil.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 13
Source File: IpUtils.java    From kob with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 14
Source File: MessageExt.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public String getBornHostString() {
    if (null != this.bornHost) {
        InetAddress inetAddress = ((InetSocketAddress) this.bornHost).getAddress();

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

    return null;
}
 
Example 15
Source File: SlaveServer.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 16
Source File: NetUtils.java    From saluki with Apache License 2.0 4 votes vote down vote up
public static String getLogHost() {
  InetAddress address = LOCAL_ADDRESS;
  return address == null ? LOCALHOST : address.getHostAddress();
}
 
Example 17
Source File: SecurityManager.java    From hottub with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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));
}
 
Example 18
Source File: OutboundSocketBinding.java    From wildfly-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: SecurityManager.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * 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));
}
 
Example 20
Source File: SecurityManager.java    From jdk8u-dev-jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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));
}