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:Main.java

public static void main(String args[]) {

    try {//  w  w  w  .ja v a  2 s  .  c  o  m
        InetAddress inetAddr = InetAddress.getByName("www.java2s.com");
        System.out.println(inetAddr.toString());

    } catch (UnknownHostException ex) {

    }
}

From source file:Main.java

public static String getLocalInetAddress(InetAddress ip) {
    return ip.toString();
}

From source file:ai.general.interbot.NetworkInterfaceInfo.java

/**
 * Returns a string representation of the specified IP address, cleaning it up if necessary.
 *
 * @param address The InetAddress to convert to a string.
 * @return A string representation of the IP address.
 *//*from w w  w. j  ava  2 s .com*/
private static String inetAddressToString(InetAddress address) {
    String result = address.toString();
    if (result.startsWith("/"))
        result = result.substring(1);
    return result;
}

From source file:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);//from w ww .  j  av  a2 s  .  c om
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}

From source file:org.apache.synapse.transport.nhttp.util.NhttpUtil.java

/**
 * This method tries to determine the hostname of the given InetAddress without
 * triggering a reverse DNS lookup.  {@link java.net.InetAddress#getHostName()}
 * triggers a reverse DNS lookup which can be very costly in cases where reverse
 * DNS fails. Tries to parse a symbolic hostname from {@link java.net.InetAddress#toString()},
 * which is documented to return a String of the form "hostname / literal IP address"
 * with 'hostname' blank if not already computed & stored in <code>address</code<.
 * <p/>// www .  j a  v a2 s  .co m
 * If the hostname cannot be determined from InetAddress.toString(),
 * the value of {@link java.net.InetAddress#getHostAddress()} is returned.
 *
 * @param address The InetAddress whose hostname has to be determined
 * @return hostsname, if it can be determined. hostaddress, if not.
 *
 * TODO: We may introduce a System property or some other method of configuration
 * TODO: which will specify whether to allow reverse DNS lookup or not
 */
public static String getHostName(InetAddress address) {
    String result;
    String hostAddress = address.getHostAddress();
    String inetAddr = address.toString();
    int index1 = inetAddr.lastIndexOf('/');
    int index2 = inetAddr.indexOf(hostAddress);
    if (index2 == index1 + 1) {
        if (index1 == 0) {
            result = hostAddress;
        } else {
            result = inetAddr.substring(0, index1);
        }
    } else {
        result = hostAddress;
    }
    return result;
}

From source file:org.apache.axis.utils.NetworkUtils.java

/**
 * Get the string defining the hostname of the system, as taken from
 * the default network adapter of the system. There is no guarantee that
 * this will be fully qualified, or that it is the hostname used by external
 * machines to access the server./*from w  ww .  j  a v  a 2s.  c om*/
 * If we cannot determine the name, then we return the default hostname,
 * which is defined by {@link #LOCALHOST}
 * @return a string name of the host.
 */
public static String getLocalHostname() {
    InetAddress address;
    String hostname;
    try {
        address = InetAddress.getLocalHost();
        //force a best effort reverse DNS lookup
        hostname = address.getHostName();
        if (hostname == null || hostname.length() == 0) {
            hostname = address.toString();
        }
    } catch (UnknownHostException noIpAddrException) {

        //this machine is not on a LAN, or DNS is unhappy
        //return the default hostname
        if (log.isDebugEnabled()) {
            log.debug("Failed to lookup local IP address", noIpAddrException);
        }
        hostname = LOCALHOST;
    }
    return hostname;
}

From source file:Messenger.TorLib.java

/**
 * This method opens a TOR socket, and does an anonymous DNS resolve through it.
 * Since Tor caches things, this is a very fast lookup if we've already connected there
 * The resolve does a gethostbyname() on the exit node.
 * @param targetHostname String containing the hostname to look up.
 * @return String representation of the IP address: "x.x.x.x"
 */// w  w w . j a  v  a2  s  .co m
static String TorResolve(String targetHostname) {
    int targetPort = 0; // we dont need a port to resolve

    try {
        Socket s = TorSocketPre(targetHostname, targetPort, TOR_RESOLVE);
        DataInputStream is = new DataInputStream(s.getInputStream());

        byte version = is.readByte();
        byte status = is.readByte();
        if (status != (byte) 90) {
            //failed for some reason, return useful exception
            throw (new IOException(ParseSOCKSStatus(status)));
        }
        int port = is.readShort();
        byte[] ipAddrBytes = new byte[4];
        is.read(ipAddrBytes);
        InetAddress ia = InetAddress.getByAddress(ipAddrBytes);
        //System.out.println("Resolved into:"+ia);
        is.close();
        String addr = ia.toString().substring(1); // clip off the "/"
        return (addr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (null);
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

/**
 * Download link and have it be the response.
 * @param req the http request//from  w ww .j  a va 2  s .  com
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c,
        String proxyHost) throws IOException {
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false);
    HttpClientParams params = new HttpClientParams();
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    HttpClient client = new HttpClient(params);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    HostConfiguration config = new HostConfiguration();
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: " + localAddress.toString());
    }
    config.setLocalAddress(localAddress);
    HttpMethod method = new GetMethod(uri.getEscapedURI());
    @SuppressWarnings("unchecked")
    Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (passThroughHeaders.contains(name)) {
            String value = req.getHeader(name);
            LOG.debug("REQ HEADER: " + name + " : " + value);
            method.setRequestHeader(name, value);
        }
    }

    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        resp.setStatus(client.executeMethod(config, method));
        for (Header header : method.getResponseHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:Utils.GenericUtils.java

public static boolean isInternetAvailable() {
    try {//ww w . j a v a  2  s . co  m
        InetAddress ipAddr = InetAddress.getByName("www.google.com");
        return !(ipAddr.toString().equals(""));
    } catch (Exception e) {
        return false;
    }
}

From source file:jp.takuo.android.mmsreq.Request.java

/**
 * Look up a host name and return the result as an int. Works if the argument
 * is an IP address in dot notation. Obviously, this can only be used for IPv4
 * addresses./* w ww  .  j  a v  a  2s . c om*/
 * @param hostname the name of the host (or the IP address)
 * @return the IP address as an {@code int} in network byte order
 */
private static int lookupHost(String hostname) {
    InetAddress inetAddress;
    try {
        inetAddress = InetAddress.getByName(hostname);
    } catch (UnknownHostException e) {
        Log.d(LOG_TAG, "Failed to resolve address: " + hostname);
        return -1;
    }
    Log.d(LOG_TAG, "Resolved Address: " + inetAddress.toString());
    byte[] addrBytes;
    int addr;
    addrBytes = inetAddress.getAddress();
    addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8)
            | (addrBytes[0] & 0xff);
    return addr;
}