Example usage for java.net InetAddress toString

List of usage examples for java.net InetAddress toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts this IP address to a String .

Usage

From source file:com.cloud.agent.Agent.java

protected void setupStartupCommand(final StartupCommand startup) {
    InetAddress addr;
    try {//  ww w. j  ava 2  s.co  m
        addr = InetAddress.getLocalHost();
    } catch (final UnknownHostException e) {
        s_logger.warn("unknow host? ", e);
        throw new CloudRuntimeException("Cannot get local IP address");
    }

    final Script command = new Script("hostname", 500, s_logger);
    final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
    final String result = command.execute(parser);
    final String hostname = result == null ? parser.getLine() : addr.toString();

    startup.setId(getId());
    if (startup.getName() == null) {
        startup.setName(hostname);
    }
    startup.setDataCenter(getZone());
    startup.setPod(getPod());
    startup.setGuid(getResourceGuid());
    startup.setResourceName(getResourceName());
    startup.setVersion(getVersion());
}

From source file:com.httrack.android.HTTrackActivity.java

/**
 * Return the IPv6 address./*w  ww .ja  va  2s .c om*/
 * 
 * @return The ipv6 address, or @c null if no IPv6 connectivity is available.
 */
protected static InetAddress getIPv6Address() {
    try {
        for (final Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces(); interfaces.hasMoreElements();) {
            final NetworkInterface iface = interfaces.nextElement();
            for (final Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses
                    .hasMoreElements();) {
                final InetAddress address = addresses.nextElement();
                Log.d(HTTrackActivity.class.getSimpleName(), "seen interface: " + address.toString());
                if (address instanceof Inet6Address) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()
                            && !address.isSiteLocalAddress() && !address.isMulticastAddress()) {
                        return address;
                    }
                }
            }
        }
    } catch (final SocketException se) {
        Log.w(HTTrackActivity.class.getSimpleName(), "could not enumerate interfaces", se);
    }
    return null;
}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void displaySystemInfo() throws SocketException {

    if (useDevConfig) {
        LOG.warn("Development environment enabled. Do not use this on a production server.");
    }// w w w  . java  2s  .  co  m

    if (LOG.isInfoEnabled()) {
        LOG.info("Version is " + ContextHolder.getContext().getVersion());
        LOG.info("Java version is " + SystemProperties.get("java.version"));
        LOG.info("Server is installed on " + hostname + "/" + hostAddress);
        LOG.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        LOG.warn("********** WARNING **********");
        LOG.warn("The system has detected that the Java runtime is GNU/GCJ");
        LOG.warn("Adito may not work correctly with this Java runtime");
        LOG.warn("you should reconfigure with a different runtime");
        LOG.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (LOG.isInfoEnabled()) {
            LOG.info("Net interface: " + netface.getName());
        }

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (LOG.isInfoEnabled()) {
                LOG.info("IP address: " + ip.toString());
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("System properties follow:");
    }
    Properties sysProps = System.getProperties();
    for (Map.Entry entry : sysProps.entrySet()) {
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("java.class.path=" + s);
                    }
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    }
                    idx += 256;
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx));
                    }
                    break;
                }
            }
        }
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.ClientHealthMonitor.java

/**
 * Returns modifiable map (changes do not effect this class) of client membershipID to connection
 * count. This is different from the map contained in this class as here the key is client
 * membershipID & not the the proxyID. It is to be noted that a given client can have multiple
 * proxies./* w  w  w.ja v  a  2  s  . co m*/
 * 
 * @param filterProxies Set identifying the Connection proxies which should be fetched. These
 *        ConnectionProxies may be from same client member or different. If it is null this would
 *        mean to fetch the Connections of all the ConnectionProxy objects.
 */
public Map getConnectedClients(Set filterProxies) {
    Map map = new HashMap(); // KEY=proxyID, VALUE=connectionCount (Integer)
    synchronized (_clientThreadsLock) {
        Iterator connectedClients = this._clientThreads.entrySet().iterator();
        while (connectedClients.hasNext()) {
            Map.Entry entry = (Map.Entry) connectedClients.next();
            ClientProxyMembershipID proxyID = (ClientProxyMembershipID) entry.getKey();// proxyID
                                                                                       // includes FQDN
            if (filterProxies == null || filterProxies.contains(proxyID)) {
                String membershipID = null;
                Set connections = (Set) entry.getValue();
                int socketPort = 0;
                InetAddress socketAddress = null;
                /// *
                Iterator serverConnections = connections.iterator();
                // Get data from one.
                while (serverConnections.hasNext()) {
                    ServerConnection sc = (ServerConnection) serverConnections.next();
                    socketPort = sc.getSocketPort();
                    socketAddress = sc.getSocketAddress();
                    membershipID = sc.getMembershipID();
                    break;
                }
                // */
                int connectionCount = connections.size();
                String clientString = null;
                if (socketAddress == null) {
                    clientString = "client member id=" + membershipID;
                } else {
                    clientString = "host name=" + socketAddress.toString() + " host ip="
                            + socketAddress.getHostAddress() + " client port=" + socketPort
                            + " client member id=" + membershipID;
                }
                Object[] data = null;
                data = (Object[]) map.get(membershipID);
                if (data == null) {
                    map.put(membershipID, new Object[] { clientString, Integer.valueOf(connectionCount) });
                } else {
                    data[1] = Integer.valueOf(((Integer) data[1]).intValue() + connectionCount);
                }
                /*
                 * Note: all client addresses are same... Iterator serverThreads = ((Set)
                 * entry.getValue()).iterator(); while (serverThreads.hasNext()) { ServerConnection
                 * connection = (ServerConnection) serverThreads.next(); InetAddress clientAddress =
                 * connection.getClientAddress(); logger.severe("getConnectedClients: proxyID=" + proxyID
                 * + " clientAddress=" + clientAddress + " FQDN=" + clientAddress.getCanonicalHostName());
                 * }
                 */
            }
        }

    }
    return map;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }/* w  w w. j a  va2s . c  o m*/

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}

From source file:com.adito.server.Main.java

private void displaySystemInfo() throws SocketException {

    ///*  w  ww .jav  a 2 s .c  om*/

    if (useDevConfig) {
        log.warn("Development environment enabled. Do not use this on a production server.");
    }

    if (log.isInfoEnabled()) {
        log.info("Version is " + ContextHolder.getContext().getVersion());
        log.info("Java version is " + SystemProperties.get("java.version"));
        log.info("Server is installed on " + hostname + "/" + hostAddress);
        log.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        log.warn("********** WARNING **********");
        log.warn("The system has detected that the Java runtime is GNU/GCJ");
        log.warn("Adito may not work correctly with this Java runtime");
        log.warn("you should reconfigure with a different runtime");
        log.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (log.isInfoEnabled())
            log.info("Net interface: " + netface.getName());

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (log.isInfoEnabled())
                log.info("IP address: " + ip.toString());
        }
    }

    if (log.isInfoEnabled())
        log.info("System properties follow:");
    Properties sysProps = System.getProperties();
    for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (log.isInfoEnabled())
                        log.info("java.class.path=" + s);
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    idx += 256;
                } else {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx));
                    break;
                }
            }
        }
    }
}

From source file:com.sslexplorer.server.Main.java

private void displaySystemInfo() throws SocketException {

    ///*  w  w w  .  j  a v  a 2  s .  c  o  m*/

    if (useDevConfig) {
        log.warn("Development environment enabled. Do not use this on a production server.");
    }

    if (log.isInfoEnabled()) {
        log.info("Version is " + ContextHolder.getContext().getVersion());
        log.info("Java version is " + SystemProperties.get("java.version"));
        log.info("Server is installed on " + hostname + "/" + hostAddress);
        log.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("SSL-Explorer does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        log.warn("********** WARNING **********");
        log.warn("The system has detected that the Java runtime is GNU/GCJ");
        log.warn("SSL-Explorer may not work correctly with this Java runtime");
        log.warn("you should reconfigure with a different runtime");
        log.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (log.isInfoEnabled())
            log.info("Net interface: " + netface.getName());

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (log.isInfoEnabled())
                log.info("IP address: " + ip.toString());
        }
    }

    if (log.isInfoEnabled())
        log.info("System properties follow:");
    Properties sysProps = System.getProperties();
    for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (log.isInfoEnabled())
                        log.info("java.class.path=" + s);
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    idx += 256;
                } else {
                    if (log.isInfoEnabled())
                        log.info("  " + entry.getKey() + "=" + val.substring(idx));
                    break;
                }
            }
        }
    }
}

From source file:orca.registry.DatabaseOperations.java

License:asdf

private boolean checkIP(String clientIP, String act_soapaxis2url) {

    if ((clientIP == null) || (act_soapaxis2url == null))
        return false;

    log.debug("Inside DatabaseOperations: checkIP()");

    String[] splitSoapUrl = act_soapaxis2url.split("//");
    String noHttp = splitSoapUrl[1];
    String[] splitNoHttp = noHttp.split(":");
    String ipSoapUrl = splitNoHttp[0];

    //System.out.println("ip in input soapUrl = " + ipSoapUrl);

    String humanReadableIP = null;
    String numericIP = null;/*from ww w .  ja  v  a2s  .c o m*/
    try {
        InetAddress address = InetAddress.getByName(ipSoapUrl);
        //System.out.println("humanreadable IP/numeric IP = " + address.toString());
        String[] splitResultGetByName = address.toString().split("/");
        humanReadableIP = splitResultGetByName[0];
        numericIP = splitResultGetByName[1];
    } catch (UnknownHostException ex) {
        log.error("Error converting IP address: " + ex.toString());
    }

    boolean result = false;
    if (clientIP.equalsIgnoreCase(numericIP)) {
        result = true;
    } else {
        if (ipSoapUrl.equalsIgnoreCase("localhost")) { // Special check: if the soapaxis url is localhost (implying test deployment) insert it into db
            result = true;
        } else {
            //System.out.println("Can't verify the identity of the client; client IP doesn't match with IP in SOAP-Axis URL of the Actor; It is also not a test deployment");
            log.debug(
                    "Can't verify the identity of the client; client IP doesn't match with IP in SOAP-Axis URL of the Actor; It is also not a test deployment");
            result = false;
        }
    }

    return result;
}

From source file:org.pentaho.di.core.Const.java

/**
 * Determins the IP address of the machine Kettle is running on.
 *
 * @return The IP address/*w w w.  jav a  2s  .c o m*/
 */
public static final String getIPAddress() throws Exception {
    Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces();
    while (enumInterfaces.hasMoreElements()) {
        NetworkInterface nwi = enumInterfaces.nextElement();
        Enumeration<InetAddress> ip = nwi.getInetAddresses();
        while (ip.hasMoreElements()) {
            InetAddress in = ip.nextElement();
            if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) {
                return in.getHostAddress();
            }
        }
    }
    return "127.0.0.1";
}

From source file:org.pentaho.di.core.Const.java

/**
 * Get the primary IP address tied to a network interface (excluding loop-back etc)
 *
 * @param networkInterfaceName/*from   www .j a v  a 2 s. co m*/
 *          the name of the network interface to interrogate
 * @return null if the network interface or address wasn't found.
 *
 * @throws SocketException
 *           in case of a security or network error
 */
public static final String getIPAddress(String networkInterfaceName) throws SocketException {
    NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName);
    Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses();
    while (ipAddresses.hasMoreElements()) {
        InetAddress inetAddress = ipAddresses.nextElement();
        if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) {
            String hostname = inetAddress.getHostAddress();
            return hostname;
        }
    }
    return null;
}