Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

In this page you can find the example usage for java.net InetAddress getHostName.

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.rhq.plugins.apache.util.HttpdAddressUtility.java

public Address getHttpdInternalVirtualHostAddressRepresentation(ApacheDirectiveTree runtimeConfig,
        String virtualHost, String serverName) {
    Address ret = null;/*from   w  w  w  .  j  av  a 2 s  .  c om*/

    if (serverName != null) {
        ret = Address.parse(serverName);
        if (!ret.isPortDefined()) {
            ret.port = 0;
        }

        //servername is taken literally and no reverse dns lookup is made
        //if the servername host is an IP address. We're done here...
    } else {
        ret = Address.parse(virtualHost);
        if (!ret.isPortDefined() || ret.isPortWildcard() || ret.isHostDefault() || ret.isHostWildcard()) {
            Address mainAddress = getHttpdInternalMainServerAddressRepresentation(runtimeConfig);

            if (!ret.isPortDefined() || ret.isPortWildcard()) {
                ret.port = mainAddress.port;
            }

            if (ret.isHostDefault() || ret.isHostWildcard()) {
                ret.host = mainAddress.host;
            }
        }

        //if the vhost hostname is an IP address, a reverse dns lookup is attempted
        //to get the actual hostname.
        //the BOGUS* constants are what the apache actually uses to identify such
        //"error" conditions.
        try {
            InetAddress iAddr = InetAddress.getByName(ret.host);
            String reverseLookup = iAddr.getHostName();
            if (iAddr.getHostAddress().equals(reverseLookup)) {
                ret.host = BOGUS_HOST_WITHOUT_REVERSE_DNS;
            } else {
                ret.host = reverseLookup;
            }
        } catch (UnknownHostException e) {
            ret.host = BOGUS_HOST_WITHOUT_FORWARD_DNS;

            //weird, as it seems, apache uses the port of the main server
            //with the unknown host even if the port was specified in the vhost
            //definition
            Address mainAddress = getHttpdInternalMainServerAddressRepresentation(runtimeConfig);
            ret.port = mainAddress.port;
        }
    }

    return ret;
}

From source file:org.rhq.helpers.rtfilter.filter.RtFilter.java

/**
 * Open the logfile for the given serverName. If serverName is localhost, then no
 * vhost portion is added to the logfile name. Otherwise the logfile name is
 * prefix + vhost + "_" + contextRoot + "_rt.log"<br/>
 * E.g. '/devel/jboss-4.0.3SP1/server/default/log/rt/snert.home.bsd.de_test_rt.log'.
 * <br/>//  w w w .  jav  a  2s  . c o  m
 * After opening the file we open a writer where we send results to. If
 * opening fails, no exceptions are thrown, as throwing any exception would cause the associated webapp to
 * fail to deploy - not something we ever want to do. Instead, the filter will simply not try to process any
 * requests (i.e. doFilter() will call the rest of the filter chain, and then just return).
 * <p/>
 * This method will set the fileDone variable to true upon success.<br/>
 * This method will set the initialized variable to false upon failure.<br/>
 * @param serverName Name of the virtual host
 */
private void openFile(String serverName) {
    String vhost = "";
    boolean found = false;

    if ("localhost".equals(serverName) || "127.0.0.1".equals(serverName)) {
        vhost = "";
        found = true;
    }

    // try to see if the user provided a mapping for this server name
    if (!found && vhostMappings.containsKey(serverName)) {
        found = true;
        vhost = vhostMappings.getProperty(serverName);
        if (vhost == null || vhost.equals(""))
            vhost = ""; // It is in the mapping, but no value set -> no vhost
        else
            vhost += "_"; // Otherwise take it and append the separator
        if (log.isDebugEnabled())
            log.debug("Vhost determined from mapping >" + vhost + "<");
    }

    // check server name against hostname and hostname.fqdn an see if they match
    if (!found && vhostMappings.containsKey(HOST_TOKEN)) {
        vhost = vhostMappings.getProperty(HOST_TOKEN);
        if (myHostName.startsWith(serverName) || myCHostName.startsWith(serverName)) {
            // Match, so take the mapping from the file
            if (vhost == null || vhost.equals("")) {
                vhost = ""; // It is in the mapping, but no value set -> no vhost
            } else {
                vhost += "_"; // Otherwise take it and append the separator
            }
            found = true;
            if (log.isDebugEnabled())
                log.debug("Vhost determined from %HOST% token >" + vhost + "<");
        }
    }

    if (!found) {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.getHostName().equalsIgnoreCase(serverName)
                    || localHost.getCanonicalHostName().equalsIgnoreCase(serverName)
                    || localHost.getHostAddress().equals(serverName)) {
                vhost = "";
                found = true;
            }
        } catch (Exception e) {
            found = false;
        }
    }

    // Nothing found? Fall back to serverName + _ as prefix
    if (!found) {
        vhost = serverName + "_"; // Not found in mapping? Take it literal + separator
    }

    // if this is a sub-context (e.g. news/radio), then replace the / by a _ to
    // prevent interpretation of the / as a dir separator.
    String contextFileName = contextName.replace('/', '_');

    String logFileName = this.logFilePrefix + vhost + contextFileName + "_rt.log";
    this.logFile = new File(this.logDirectory, logFileName);
    log.info("-- Filter openFile: Writing response-time log for webapp with context root '" + this.contextName
            + "' to '" + this.logFile + "' (hashCode=" + hashCode() + ")...");
    boolean append = true;
    try {
        openFileWriter(append);
        fileDone = true;
    } catch (Exception e) {
        // reset the initialized flag in case of error
        this.initialized = false;
        log.warn(e.getMessage());
    }

}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public Socket createSocket(InetAddress host, int port, int connectTimeout) throws IOException {
    Socket s = new Socket();
    s.connect(new InetSocketAddress(host, port), connectTimeout);
    SSLSocketFactory sslsf = sslc.getSocketFactory();
    SSLSocket ssls = (SSLSocket) sslsf.createSocket(s, host.getHostName(), port, true);
    if (protocols != null) {
        ssls.setEnabledProtocols(protocols);
    } else {//from ww  w . j a va  2s.co m
        String[] protocols = ssls.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        ssls.setEnabledProtocols(set.toArray(new String[0]));
    }
    applyCiphers(ssls);
    return ssls;
}

From source file:org.apache.hadoop.fs.loadGenerator.LoadGenerator.java

/** Constructor */
public LoadGenerator() throws IOException, UnknownHostException {
    InetAddress addr = InetAddress.getLocalHost();
    hostname = addr.getHostName();
    Arrays.fill(WRITE_CONTENTS, (byte) 'a');
}

From source file:org.rhq.plugins.jbossas5.ApplicationServerDiscoveryComponent.java

public String formatServerName(String bindingAddress, String jnpPort, String hostname, String configurationName,
        boolean isRhq) {

    if (isRhq) {/*ww  w .  j ava2s.c  o m*/
        return hostname + " RHQ Server";
    } else {
        String hostnameToUse = hostname;

        if (bindingAddress != null) {
            try {
                InetAddress bindAddr = InetAddress.getByName(bindingAddress);
                if (!bindAddr.isAnyLocalAddress()) {
                    //if the binding address != 0.0.0.0
                    hostnameToUse = bindAddr.getHostName();
                }
            } catch (UnknownHostException e) {
                //this should not happen?
                log.warn("Unknown hostname passed in as the binding address for JBoss AS server discovery: "
                        + bindingAddress);
            }
        }

        if (jnpPort != null) {
            hostnameToUse += ":" + jnpPort;
        }

        return hostnameToUse + " " + configurationName;
    }
}

From source file:net.i2p.util.I2PSSLSocketFactory.java

/**
 * Returns a socket to the host./*w  ww.  j a  v a2  s . c  om*/
 *
 * An InetAddress argument created with an IP address (instead of a host name)
 * is not recommended, as this will perform a reverse DNS lookup to
 * get the host name for certificate validation, which will probably then fail.
 *
 * Hostname validation is skipped for localhost addresses, but you still
 * must trust the certificate.
 *
 * @since 0.9.9
 */
public Socket createSocket(InetAddress host, int port) throws IOException {
    SSLSocket rv = (SSLSocket) _factory.createSocket(host, port);
    setProtocolsAndCiphers(rv);
    String name = host.getHostName();
    verifyHostname(_context, rv, name);
    return rv;
}

From source file:com.btobits.automator.mail.smtp.SMTPProcessor.java

/**
 * Entrypoint for the Thread, this method handles the interaction with
 * the client socket.//from   w w w  .j  ava 2  s  .c  o m
 */
public void run() {

    try {
        //Set the socket to timeout every 10 seconds so it does not
        //just block forever.
        serverSocket.setSoTimeout(10 * 1000);
    } catch (SocketException se) {
        log.fatal("Error initializing Socket Timeout in SMTPProcessor");
    }

    while (running) {
        try {
            socket = serverSocket.accept();

            //Set the socket to timeout after 10 seconds
            socket.setSoTimeout(10 * 1000);

            //Prepare the input and output streams.
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            InetAddress remoteAddress = socket.getInetAddress();
            clientIp = remoteAddress.getHostAddress();

            if (log.isInfoEnabled()) {
                log.info(remoteAddress.getHostName() + "(" + clientIp + ") socket connected via SMTP.");
            }

            write(WELCOME_MESSAGE);

            //Initialize the input message.
            message = new SMTPMessage();

            //Parses the input for commands and delegates to the appropriate methods.
            handleCommands();

        } catch (InterruptedIOException iioe) {
            //This is fine, it should time out every 10 seconds if
            //a connection is not made.
        }
        //If any exception gets to here uncaught, it means we should just disconnect.
        catch (Throwable e) {
            log.debug("Disconnecting Exception:", e);
            log.info("Disconnecting");
            try {
                write(MESSAGE_DISCONNECT);
            } catch (Exception e1) {
                log.debug("Error sending disconnect message.", e1);
                //Nothing to do.
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException ioe) {
                log.debug("Error disconnecting.", ioe);
                //Nothing to do.
            }
        }
    }
    log.warn("SMTPProcessor shut down gracefully");
}

From source file:org.apache.jmeter.util.JMeterUtils.java

private static void getLocalHostDetails() {
    InetAddress localHost = null;
    try {//www.j  a  v a  2s. c o m
        localHost = InetAddress.getLocalHost();
    } catch (UnknownHostException e1) {
        log.error("Unable to get local host IP address.", e1);
        return; // TODO - perhaps this should be a fatal error?
    }
    localHostIP = localHost.getHostAddress();
    localHostName = localHost.getHostName();
    localHostFullName = localHost.getCanonicalHostName();
}

From source file:io.servicecomb.serviceregistry.TestRegistry.java

@Test
public void testRegistryUtilGetHostName(@Mocked InetAddress ethAddress) {
    new Expectations(NetUtils.class) {
        {//from www. j a va  2s  . com
            NetUtils.getHostName();
            result = "testHostName";
        }
    };
    String host = RegistryUtils.getPublishHostName();
    Assert.assertEquals("testHostName", host);

    inMemoryConfig.addProperty(PUBLISH_ADDRESS, "127.0.0.1");
    Assert.assertEquals("127.0.0.1", RegistryUtils.getPublishHostName());

    new Expectations(DynamicPropertyFactory.getInstance()) {
        {
            ethAddress.getHostName();
            result = "testHostName";
            NetUtils.ensureGetInterfaceAddress("eth100");
            result = ethAddress;
        }
    };
    inMemoryConfig.addProperty(PUBLISH_ADDRESS, "{eth100}");
    Assert.assertEquals("testHostName", RegistryUtils.getPublishHostName());
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private final void processAccept(SelectionKey key) throws Exception {

    // Check TCP/IP access
    if (hosts != null || addresses != null) {
        Socket socket = ((SocketChannel) key.channel()).socket();
        InetAddress inetAddress = socket.getInetAddress();
        if (hosts != null) {
            String host = inetAddress.getHostName();
            if (host == null || host.length() == 0 || host.equals("127.0.0.1")) {
                host = "localhost";
            } else {
                host = host.toLowerCase();
                if (host.equals("localhost.localdomain")) {
                    host = "localhost";
                }/*from w ww . jav a  2 s .co m*/
            }
            if (!isHostMatch(host)) {
                throw new Exception("Connection refused, forbidden hostname (" + host + ")!");
            }
        }
        if (addresses != null) {
            String address = inetAddress.getHostAddress();
            if (address == null || address.length() == 0) {
                address = "127.0.0.1";
            }
            if (!isAddressMatch(address)) {
                throw new Exception("Connection refused, forbidden IP-address (" + address + ")!");
            }
        }
    }
}