Example usage for java.net InetAddress getHostAddress

List of usage examples for java.net InetAddress getHostAddress

Introduction

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

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation.

Usage

From source file:copter.ServerConnection.java

private String getIpAddress() {
    String hostAddress = null;//from   w  w w . j  a  v  a2s . co m
    try {
        Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
        for (; n.hasMoreElements();) {
            NetworkInterface e = n.nextElement();

            Enumeration<InetAddress> a = e.getInetAddresses();
            for (; a.hasMoreElements();) {
                InetAddress addr = a.nextElement();
                hostAddress = addr.getHostAddress();
                break;
            }
            break;
        }
    } catch (Exception ex) {
        logger.log(ex.getMessage());
    }
    return hostAddress;
}

From source file:de.codecentric.boot.admin.config.AdminClientProperties.java

public String getServiceUrl() {
    if (serviceUrl != null) {
        return serviceUrl;
    }/*from  w w  w.  j a v  a  2  s .  c  o m*/

    if (serverPort == null) {
        throw new IllegalStateException("serviceUrl must be set when deployed to servlet-container");
    }

    if (preferIp) {
        InetAddress address = server.getAddress();
        if (address == null) {
            address = getHostAddress();
        }
        return append(createLocalUri(address.getHostAddress(), serverPort), server.getContextPath());

    }
    return append(createLocalUri(getHostAddress().getCanonicalHostName(), serverPort), server.getContextPath());
}

From source file:net.sbbi.upnp.Discovery.java

/**
 * Sends an SSDP search message on the network
 * @param src the sender ip/*from   w w w .java 2 s.  co m*/
 * @param ttl the time to live
 * @param mx the mx field
 * @param searchTarget the search target
 * @throws IOException if some IO errors occurs during search
 */
public static void sendSearchMessage(InetAddress src, int ttl, int mx, String searchTarget) throws IOException {

    int bindPort = DEFAULT_SSDP_SEARCH_PORT;
    String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort");
    if (port != null) {
        bindPort = Integer.parseInt(port);
    }
    InetSocketAddress adr = new InetSocketAddress(InetAddress.getByName(Discovery.SSDP_IP),
            Discovery.SSDP_PORT);

    java.net.MulticastSocket skt = new java.net.MulticastSocket(null);
    skt.bind(new InetSocketAddress(src, bindPort));
    skt.setTimeToLive(ttl);
    StringBuffer packet = new StringBuffer();
    packet.append("M-SEARCH * HTTP/1.1\r\n");
    packet.append("HOST: 239.255.255.250:1900\r\n");
    packet.append("MAN: \"ssdp:discover\"\r\n");
    packet.append("MX: ").append(mx).append("\r\n");
    packet.append("ST: ").append(searchTarget).append("\r\n").append("\r\n");
    if (log.isDebugEnabled())
        log.debug("Sending discovery message on 239.255.255.250:1900 multicast address form ip "
                + src.getHostAddress() + ":\n" + packet.toString());
    String toSend = packet.toString();
    byte[] pk = toSend.getBytes();
    skt.send(new DatagramPacket(pk, pk.length, adr));
    skt.disconnect();
    skt.close();
}

From source file:com.scottieknows.test.cassandra.CassandraClusterManager.java

/**
 * @return {@link Map} of interface name to address
 *///from  w w w.jav a  2 s. c  om
Map<String, String> getIpsStartingWith(String prefix) {
    if (prefix == null) {
        return Collections.emptyMap();
    }
    try {
        Map<String, String> rtn = new HashMap<>();
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface i = networkInterfaces.nextElement();
            Enumeration<InetAddress> addrs = i.getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress addr = addrs.nextElement();
                String hostAddress = addr.getHostAddress();
                if (hostAddress.startsWith(prefix)) {
                    rtn.put(i.getName(), hostAddress);
                }
            }
        }
        return rtn;
    } catch (SocketException e) {
        throw new RuntimeException("could not retrieve network interfaces: " + e, e);
    }
}

From source file:com.reversemind.hypergate.server.HyperGateServer.java

private String getIpAddress() {
    Set<String> ipSet = new TreeSet<String>();
    Enumeration<NetworkInterface> n = null;

    try {/*  ww  w. j  a  v a  2s.c  o m*/
        n = NetworkInterface.getNetworkInterfaces();

        for (; n.hasMoreElements();) {
            NetworkInterface e = n.nextElement();
            Enumeration<InetAddress> a = e.getInetAddresses();
            for (; a.hasMoreElements();) {
                InetAddress inetAddress = a.nextElement();
                if (inetAddress.getHostAddress() != null) {
                    ipSet.add(inetAddress.getHostAddress());
                }
            }
        }

        if (ipSet != null && ipSet.size() > 0) {
            for (String ip : ipSet) {
                if (!ip.equals("127.0.0.1") & !ip.equalsIgnoreCase("localhost")) {
                    return ip;
                }
            }
        }

    } catch (SocketException se) {
        LOG.error("Socket exception", se);
    }

    return "localhost";
}

From source file:com.qpark.eip.core.spring.lockedoperation.dao.LockedOperationDaoImpl.java

private void setupHostValues() {
    if (this.hostName == null) {
        try {/*  w w  w. j a  v  a2s .co m*/
            InetAddress localaddr = InetAddress.getLocalHost();
            this.hostAddress = localaddr.getHostAddress();
            this.hostName = localaddr.getHostName();
        } catch (UnknownHostException e) {
            this.logger.error(e.getMessage(), e);
            this.hostName = "localhost";
        }
    }
}

From source file:eu.musesproject.client.contextmonitoring.sensors.DeviceProtectionSensor.java

public String getIPAddress(boolean useIPv4) {
    try {//from ww w  .  j a  v a2  s  . c  o  m
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%');
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
    } // for now eat exceptions
    return "";
}

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

/**
 * DNS????????//from   w  ww. j a v a2 s . c  o  m
 *
 * @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;
    }
}

From source file:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Converts the passed in siteUrl to be https if not already or not local.
 * //from  ww  w . j  a va 2  s  .  c  om
 * @param siteUrl The url of a cadmium site.
 * @return The passed in siteUrl or the same url but converted to https.
 */
protected String getSecureBaseUrl(String siteUrl) {
    if (!siteUrl.startsWith("http://") && !siteUrl.startsWith("https://")) {
        siteUrl = "http://" + siteUrl;
    }
    Matcher urlMatcher = URL_PATTERN.matcher(siteUrl);
    if (urlMatcher.matches()) {
        logger.debug("Url matches [{}]", siteUrl);
        boolean local = false;
        try {
            logger.debug("Checking if host [{}] is local", urlMatcher.group(1));
            InetAddress hostAddr = InetAddress.getByName(urlMatcher.group(1));
            local = hostAddr.isLoopbackAddress() || hostAddr.isSiteLocalAddress();
            logger.debug("IpAddress [{}] local: {}", hostAddr.getHostAddress(), local);
        } catch (UnknownHostException e) {
            logger.warn("Hostname not found [" + siteUrl + "]", e);
        }
        if (!local) {
            return siteUrl.replaceFirst("http://", "https://");
        }
    }
    return siteUrl;
}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

protected String getUri() {
    final InetAddress addr = (InetAddress) tomcat.getConnector().getAttribute("address");

    return protocol.getScheme() + addr.getHostAddress() + ":" + getPort();
}