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:io.tilt.minka.domain.NetworkShardIDImpl.java

private InetAddress findSiteAddress(final Config config) {
    InetAddress fallback = null;/* w  w w. j av  a  2  s. c  om*/
    try {
        final String niName = config.getFollowerUseNetworkInterfase();
        logger.info("{}: Looking for configured network interfase: {}", getClass().getSimpleName(), niName);
        final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            final NetworkInterface ni = nis.nextElement();
            if (niName.contains(ni.getName())) {
                logger.info("{}: Interfase found: {}, looking for a Site address..", getClass().getSimpleName(),
                        ni.getName());
                final Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    final InetAddress ia = ias.nextElement();
                    if (ia.isSiteLocalAddress()) {
                        logger.info("{}: Host site address found: {}:{} with HostName {}",
                                getClass().getSimpleName(), ia.getHostAddress(), config.getBrokerServerPort(),
                                ia.getHostName());
                        return ia;
                    } else {
                        fallback = ia;
                        logger.warn("{}: Specified interfase: {} is not a site address!!, "
                                + "you should specify a non local-only valid interfase !! where's your lan?",
                                getClass().getSimpleName(), ia.getHostAddress());
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("{}: Cannot build shard id value with hostname", getClass().getSimpleName(), e);
    }
    logger.error("{}: Site network interfase not found !", getClass().getSimpleName());
    return fallback;
}

From source file:com.adaptris.http.HttpListener.java

/**
 * @see java.lang.Object#toString()/*from   ww  w  .  java  2  s. co m*/
 */
@Override
public String toString() {
    String className = this.getClass().getSimpleName();
    InetAddress a = null;
    try {
        a = InetAddress.getLocalHost();
    } catch (Exception ignoredIntentionally) {
        ;
    }
    StringBuffer sb = new StringBuffer(className);
    sb.append(" on ");
    sb.append(a != null ? a.getHostName() + ":" : "");
    sb.append(listenPort);
    return sb.toString();
}

From source file:org.esco.cas.client.CasSingleLogoutClusterFilter.java

@Override
public void init(final FilterConfig config) throws ServletException {
    // Get local hostName on initialization
    this.clientHostName = config.getInitParameter(CasSingleLogoutClusterFilter.CLIENT_HOSTNAME_PARAMETER);

    if (!StringUtils.hasText(this.clientHostName)) {
        try {//  w  ww  . j a va  2 s  .c  om

            final InetAddress localMachine = InetAddress.getLocalHost();
            this.clientHostName = localMachine.getHostName();
            CasSingleLogoutClusterFilter.LOG.info("Detected Hostname for local machine: [{}]",
                    this.clientHostName);
        } catch (UnknownHostException e) {
            final String errorMsg = String.format(
                    "Error while detecting IP Address of server. You need to configure the filter parameter: [%1$s]",
                    CasSingleLogoutClusterFilter.CLIENT_HOSTNAME_PARAMETER);
            CasSingleLogoutClusterFilter.LOG.error(errorMsg, e);
        }
    }

    // Get comma delimited list of peer dns names from a filter config
    final String peerList = config.getInitParameter(CasSingleLogoutClusterFilter.PEERS_PARAMETER);
    if (!StringUtils.hasText(peerList)) {
        CasSingleLogoutClusterFilter.LOG
                .warn("No peers URL configured the CasSingleLogoutClusterFilter will not works !");
    }

    String[] peersDescription = peerList.split(",");
    for (String peerDescription : peersDescription) {
        try {
            this.peers.add(new Peer(peerDescription));
        } catch (MalformedURLException e) {
            // We don't block the webapp initializiation. Just log an error.
            CasSingleLogoutClusterFilter.LOG.error(
                    "Malformed peer URL [{}] among CasSingleLogoutClusterFilter peers !", peerDescription);
            //throw new ServletException("Malformed URL among CasSingleLogoutClusterFilter peers !", e);
        }
    }

    if (!StringUtils.hasText(this.clientHostName)) {
        CasSingleLogoutClusterFilter.LOG
                .warn("No client hostname configured the CasSingleLogoutClusterFilter may not works !");
    }

    if (CollectionUtils.isEmpty(this.peers)) {
        CasSingleLogoutClusterFilter.LOG
                .warn("No valid peers URL configured the CasSingleLogoutClusterFilter will not works !");
    }

    CasSingleLogoutClusterFilter.LOG.info("Client hostname: [{}]", this.clientHostName);
    CasSingleLogoutClusterFilter.LOG.info("SLO cluster peers: [{}]", peerList.toString());
}

From source file:org.apache.synapse.core.axis2.SynapseModule.java

public void init(ConfigurationContext configurationContext, AxisModule axisModule) throws AxisFault {
    try {// w  ww.j  a va  2 s.c o m
        InetAddress addr = InetAddress.getLocalHost();
        if (addr != null) {
            // Get IP Address
            String ipAddr = addr.getHostAddress();
            if (ipAddr != null) {
                MDC.put("ip", ipAddr);
            }

            // Get hostname
            String hostname = addr.getHostName();
            if (hostname == null) {
                hostname = ipAddr;
            }
            MDC.put("host", hostname);
        }

    } catch (UnknownHostException e) {
        log.warn("Unable to report hostname or IP address for tracing", e);
    }

    log.info("Deploying the Synapse service..");
    // Dynamically initialize the Synapse Service and deploy it into Axis2
    AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
    AxisService synapseService = new AxisService(SYNAPSE_SERVICE_NAME);
    AxisOperation mediateOperation = new InOutAxisOperation(MEDIATE_OPERATION_Q_NAME);
    mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
    synapseService.addOperation(mediateOperation);
    axisCfg.addService(synapseService);

    // Initializing the SynapseEnvironment and SynapseConfiguration
    log.info("Initializing the Synapse configuration ...");
    SynapseConfiguration synCfg = initializeSynapse(configurationContext);

    log.info("Deploying Proxy services...");
    Iterator iter = synCfg.getProxyServices().iterator();
    while (iter.hasNext()) {
        ProxyService proxy = (ProxyService) iter.next();
        proxy.buildAxisService(synCfg, axisCfg);
        if (!proxy.isStartOnLoad()) {
            proxy.stop(synCfg);
        }
    }

    log.info("Synapse initialized successfully...!");
}

From source file:com.vivareal.logger.appender.UDPAppender.java

/**
 * Sends UDP packets to the <code>address</code> and <code>port</code>.
 *//*w  w w.j a  va2s. c  o m*/
public UDPAppender(InetAddress address, int port) {
    this.address = address;
    this.remoteHost = address.getHostName();
    this.port = port;
    connect(address, port);
}

From source file:org.apereo.portal.PortalInfoProviderImpl.java

protected String getNetworkInterfaceName(String networkInterfaceName) {
    if (networkInterfaceName == null) {
        return null;
    }//  w  ww. j av a 2 s  .com

    this.logger.info("Attempting to resolve serverName using NetworkInterface named ({})",
            networkInterfaceName);

    final NetworkInterface networkInterface;
    try {
        networkInterface = NetworkInterface.getByName(networkInterfaceName);
    } catch (SocketException e) {
        logger.warn("Failed to get NetworkInterface for name (" + networkInterfaceName + ").", e);
        return null;
    }

    if (networkInterface == null) {
        logger.warn("No NetworkInterface could be found for name (" + networkInterfaceName
                + "). Available interface names: " + getNetworkInterfaceNames());
        return null;
    }

    final Enumeration<InetAddress> inetAddressesEnum = networkInterface.getInetAddresses();
    if (!inetAddressesEnum.hasMoreElements()) {
        logger.warn("NetworkInterface (" + networkInterface.getName()
                + ") has no InetAddresses to get a name from.");
        return null;
    }

    final InetAddress inetAddress = inetAddressesEnum.nextElement();
    if (inetAddressesEnum.hasMoreElements()) {
        logger.warn("NetworkInterface (" + networkInterface.getName()
                + ") has more than one InetAddress, the hostName of the first will be returned.");
    }

    return inetAddress.getHostName();
}

From source file:com.googlecode.jsendnsca.MessagePayload.java

/**
 * Set the hostname in the passive check
 *
 * @param useCanonical true to use this machines fully qualified domain name, false
 *                     to use the short hostname
 */// www  .j  av  a 2s.  co  m
public void setHostname(boolean useCanonical) {
    InetAddress ipAddress;
    try {
        ipAddress = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new UnknownHostRuntimeException(e);
    }
    if (useCanonical) {
        this.hostname = ipAddress.getCanonicalHostName();
    } else {
        this.hostname = ipAddress.getHostName();
    }
}

From source file:com.sshtools.j2ssh.agent.SshAgentClient.java

/**
 * Send a forwarding notice.//from ww w  .  j a  v  a  2s. c o m
 *
 * @throws IOException if an IO error occurs
 */
protected void sendForwardingNotice() throws IOException {
    InetAddress addr = InetAddress.getLocalHost();

    SshAgentForwardingNotice msg = new SshAgentForwardingNotice(addr.getHostName(), addr.getHostAddress(), 22);

    sendMessage(msg);
}

From source file:org.springframework.integration.ip.tcp.connection.TcpConnectionSupport.java

/**
 * Creates a {@link TcpConnectionSupport} object and publishes a
 * {@link TcpConnectionOpenEvent}, if an event publisher is provided.
 * @param socket the underlying socket./*from   www  .  j av a2s.  com*/
 * @param server true if this connection is a server connection
 * @param lookupHost true if reverse lookup of the host name should be performed,
 * otherwise, the ip address will be used for identification purposes.
 * @param applicationEventPublisher the publisher to which open, close and exception events will
 * be sent; may be null if event publishing is not required.
 * @param connectionFactoryName the name of the connection factory creating this connection; used
 * during event publishing, may be null, in which case "unknown" will be used.
 */
public TcpConnectionSupport(Socket socket, boolean server, boolean lookupHost,
        ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName) {
    this.server = server;
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
        this.hostAddress = inetAddress.getHostAddress();
        if (lookupHost) {
            this.hostName = inetAddress.getHostName();
        } else {
            this.hostName = this.hostAddress;
        }
    }
    int port = socket.getPort();
    this.connectionId = this.hostName + ":" + port + ":" + UUID.randomUUID().toString();
    try {
        this.soLinger = socket.getSoLinger();
    } catch (SocketException e) {
    }
    this.applicationEventPublisher = applicationEventPublisher;
    if (connectionFactoryName != null) {
        this.connectionFactoryName = connectionFactoryName;
    }
    this.publishConnectionOpenEvent();
    if (logger.isDebugEnabled()) {
        logger.debug("New connection " + this.getConnectionId());
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????/*  w  w w  . j a va2s .  com*/
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

        bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException e) {
                    m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(DNS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}