Example usage for java.net InetAddress getAllByName

List of usage examples for java.net InetAddress getAllByName

Introduction

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

Prototype

public static InetAddress[] getAllByName(String host) throws UnknownHostException 

Source Link

Document

Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.

Usage

From source file:com.bright.assetbank.application.servlet.ApplicationActionServlet.java

public void init()/*     */ throws ServletException
/*     */ {//from   w w w .j a  va  2s  . co  m
    /*     */ try
    /*     */ {
        /*  82 */ setupGlobalSettings();
        /*     */ }
    /*     */ catch (Throwable te)
    /*     */ {
        /*  87 */ System.out.println("ApplicationActionServlet.init: Bn2Exception: " + te.getMessage());
        /*     */ }
    /*     */
    /*  91 */ String[] noStoreActions = getServletConfig().getInitParameter("noStoreGetActions")
            .split("[,\t\n ]+");
    /*  92 */ this.m_noStoreActionSet = new HashSet((int) ((noStoreActions.length + 1) * 1.5D));
    /*  93 */ this.m_noStoreActionSet.addAll(Arrays.asList(noStoreActions));
    /*     */
    /*  95 */ boolean bSuspendLicenseValidation = false;
    /*  96 */ boolean bLicenseValid = false;
    /*  97 */ boolean bLicenseException = false;
    /*  98 */ int iLicenseDaysLeft = 0;
    /*  99 */ String sLicenseDate = "";
    /* 100 */ String sLicenseType = "";
    /* 101 */ boolean bLicenseNeverExpires = false;
    /* 102 */ boolean bLicenseIPUnbound = false;
    /* 103 */ boolean bLicenseWebappUnbound = false;
    /*     */
    /* 106 */ String sLicenseIPs = "";
    /*     */
    /* 109 */ String sLicenseWebapps = "";
    /*     */ try
    /*     */ {
        /* 114 */ LicenseManager licManager = LicenseManager.getInstance();
        /* 115 */ bLicenseValid = licManager.isValid();
        /* 116 */ iLicenseDaysLeft = licManager.daysLeft();
        /* 117 */ sLicenseIPs = licManager.getFeature("IP");
        /* 118 */ sLicenseWebapps = licManager.getFeature("Webapp");
        /* 119 */ sLicenseDate = licManager.getFeature("Expiration");
        /* 120 */ sLicenseType = licManager.getFeature("Type");
        /*     */ }
    /*     */ catch (Throwable e)
    /*     */ {
        /* 124 */ bLicenseValid = false;
        /* 125 */ bLicenseException = true;
        /*     */ }
    /*     */
    /* 128 */ bLicenseNeverExpires = (iLicenseDaysLeft == 0) && ((sLicenseDate == null)
            || (sLicenseDate.length() == 0) || (sLicenseDate.compareToIgnoreCase("never") == 0));
    /* 129 */ bLicenseIPUnbound = (sLicenseIPs == null) || (sLicenseIPs.length() == 0);
    /* 130 */ bLicenseWebappUnbound = (sLicenseWebapps == null) || (sLicenseWebapps.length() == 0);
    /*     */
    /* 133 */ boolean bIPValid = false;
    /* 134 */ boolean bIPException = false;
    /* 135 */ String sLocalIPs = "";
    /* 136 */ Vector vecLocalIPs = new Vector();
    /* 137 */ String sValidIP = "";
    /*     */
    /* 139 */ if (bLicenseIPUnbound)
    /*     */ {
        /* 141 */ bIPValid = true;
        /*     */ }
    /*     */ else
    /*     */ {
        /*     */ try
        /*     */ {
            /* 148 */ Vector vecLicensedIPs = StringUtil.convertToVector(sLicenseIPs, ",");
            /*     */
            /* 151 */ InetAddress ipLocalhost = InetAddress.getLocalHost();
            /* 152 */ InetAddress[] arrAddress = InetAddress.getAllByName(ipLocalhost.getHostName());
            /* 153 */ for (int i = 0; i < arrAddress.length; i++)
            /*     */ {
                /* 158 */ String sIP = arrAddress[i].getHostAddress().trim();
                /* 159 */ vecLocalIPs.add(sIP);
                /* 160 */ sLocalIPs = sLocalIPs + sIP + ", ";
                /*     */ }
            /*     */
            /* 164 */ Iterator it = vecLicensedIPs.iterator();
            /* 165 */ while (it.hasNext())
            /*     */ {
                /* 167 */ String sLicensedIP = (String) it.next();
                /*     */
                /* 169 */ Iterator itLocal = vecLocalIPs.iterator();
                /* 170 */ while (itLocal.hasNext())
                /*     */ {
                    /* 172 */ String sLocalIP = (String) itLocal.next();
                    /*     */
                    /* 174 */ if (sLicensedIP.trim().compareToIgnoreCase(sLocalIP) == 0)
                    /*     */ {
                        /* 176 */ bIPValid = true;
                        /* 177 */ sValidIP = sLocalIP;
                        /* 178 */ break;
                        /*     */ }
                    /*     */ }
                /*     */
                /* 182 */ if (bIPValid)
                /*     */ {
                    /*     */ break;
                    /*     */ }
                /*     */ }
            /*     */
            /*     */ }
        /*     */ catch (UnknownHostException e)
        /*     */ {
            /* 191 */ bIPValid = false;
            /* 192 */ bIPException = true;
            /*     */ }
        /*     */
        /*     */ }
    /*     */
    /* 197 */ boolean bWebappValid = false;
    /* 198 */ String sLocalWebapp = "";
    /*     */
    /* 200 */ if (bLicenseWebappUnbound)
    /*     */ {
        /* 202 */ bWebappValid = true;
        /*     */ }
    /*     */ else
    /*     */ {
        /* 207 */ Vector vecLicensedWebapps = StringUtil.convertToVector(sLicenseWebapps, ",");
        /*     */
        /* 210 */ String sApplicationPath = getServletContext().getRealPath("");
        /* 211 */ File dir = new File(sApplicationPath);
        /* 212 */ sLocalWebapp = dir.getName();
        /*     */
        /* 215 */ Iterator it = vecLicensedWebapps.iterator();
        /* 216 */ while (it.hasNext())
        /*     */ {
            /* 218 */ String sLicensedWebapp = (String) it.next();
            /*     */
            /* 220 */ if (sLicensedWebapp.trim().compareToIgnoreCase(sLocalWebapp) == 0)
            /*     */ {
                /* 222 */ bWebappValid = true;
                /* 223 */ break;
                /*     */ }
            /*     */ }
        /*     */
        /*     */ }
    /*     */
    /* 229 */ boolean bTypeValid = false;
    /*     */
    /* 231 */ bTypeValid = checkLicenseType(sLicenseType);
    /*     */
    /* 234 */ if (((!bLicenseValid) || (!bIPValid) || (!bWebappValid) || (!bTypeValid))
            && (!bSuspendLicenseValidation))
    /*     */ {
        /* 236 */ GlobalApplication.getInstance().suspendWebsite();
        /*     */ }
    /*     */
    /* 240 */ if (AssetBankSettings.isApplicationUpdateInProgress())
    /*     */ {
        /* 243 */ GlobalApplication.getInstance().setSkipStartups(true);
        /*     */ }
    /*     */
    /* 247 */ if (AssetBankSettings.getRequiresEndorsedLibs())
    /*     */ {
        /* 249 */ addEndorsedLibToSystemProperties();
        /*     */ }
    /*     */
    /* 253 */ super.init();
    /*     */
    /* 256 */ if (!bLicenseValid)
    /*     */ {
        /* 258 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed.");
        /*     */ }
    /* 260 */ if (bLicenseException)
    /*     */ {
        /* 262 */ GlobalApplication.getInstance().getLogger().error(
                "ApplicationActionServlet.init: Error in license validation is most likely due to missing license file. Check under WEB-INF/classes.");
        /*     */ }
    /* 264 */ if (!bTypeValid)
    /*     */ {
        /* 266 */ GlobalApplication.getInstance().getLogger().info(
                "ApplicationActionServlet.init: License validation failed: License is of the incorrect type");
        /*     */ }
    /* 268 */ if (bIPValid)
    /*     */ {
        /* 270 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License valid for IP address: " + sValidIP);
        /*     */ }
    /*     */ else
    /*     */ {
        /* 274 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed: IP address " + sLocalIPs
                        + " not in permitted range: " + sLicenseIPs);
        /*     */ }
    /* 276 */ if (bIPException)
    /*     */ {
        /* 278 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: Error in reading IP address of local host server.");
        /*     */ }
    /* 280 */ if (bWebappValid)
    /*     */ {
        /* 282 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License valid for webapp: " + sLocalWebapp);
        /*     */ }
    /*     */ else
    /*     */ {
        /* 286 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed: webapp " + sLocalWebapp
                        + " not in permitted range: " + sLicenseWebapps);
        /*     */ }
    /*     */
    /* 289 */ if ((bLicenseNeverExpires) && (bLicenseValid))
    /*     */ {
        /* 291 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License never expires.");
        /*     */ }
    /*     */ else
    /*     */ {
        /* 295 */ if (iLicenseDaysLeft < 0)
        /*     */ {
            /* 297 */ GlobalApplication.getInstance().getLogger()
                    .error("ApplicationActionServlet.init: License expired!");
            /*     */ }
        /* 299 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License days left: " + iLicenseDaysLeft);
        /*     */ }
    /*     */
    /* 303 */ GlobalApplication.getInstance().getLogger().info(
            "ApplicationActionServlet.init: Application Version: " + AssetBankSettings.getApplicationVersion());
    /*     */
    /* 307 */ ABUserProfile.setUserProfileFactory(new ABUserProfileFactory());
    /*     */
    /* 312 */ HTTPUtil.setProxySettings();
    /*     */ }

From source file:com.android.strictmodetest.StrictModeActivity.java

/** Called when the activity is first created. */
@Override/*from  w ww  .ja  va  2s . c  om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cr = getContentResolver();
    final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null);

    final Button readButton = (Button) findViewById(R.id.read_button);
    readButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Cursor c = null;
            try {
                c = db.rawQuery("SELECT * FROM foo", null);
            } finally {
                if (c != null)
                    c.close();
            }
        }
    });

    final Button writeButton = (Button) findViewById(R.id.write_button);
    writeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
        }
    });

    final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button);
    writeLoopButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            long startTime = SystemClock.uptimeMillis();
            int iters = 1000;
            BlockGuard.Policy policy = BlockGuard.getThreadPolicy();
            for (int i = 0; i < iters; ++i) {
                policy.onWriteToDisk();
            }
            long endTime = SystemClock.uptimeMillis();
            Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg="
                    + (endTime - startTime) / (double) iters);
        }
    });

    final Button dnsButton = (Button) findViewById(R.id.dns_button);
    dnsButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)");
            try {
                InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com");
                for (int i = 0; i < addrs.length; ++i) {
                    Log.d(TAG, "got: " + addrs[i]);
                }
            } catch (java.net.UnknownHostException e) {
                Log.d(TAG, "DNS error: " + e);
            }
        }
    });

    final Button httpButton = (Button) findViewById(R.id.http_button);
    httpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Note: not using AndroidHttpClient, as that comes with its
                // own pre-StrictMode network-on-Looper thread check.  The
                // intent of this test is that we test the network stack's
                // instrumentation for StrictMode instead.
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico"));
                Log.d(TAG, "Fetched http response: " + res);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http2Button = (Button) findViewById(R.id.http2_button);
    http2Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // Usually this ends up tripping in DNS resolution,
                // so see http3Button below, which connects directly to an IP
                InputStream is = new URL("http://www.android.com/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button http3Button = (Button) findViewById(R.id.http3_button);
    http3Button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                // One of Google's web IPs, as of 2010-06-16....
                InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream();
                Log.d(TAG, "Got input stream: " + is);
            } catch (IOException e) {
                Log.d(TAG, "HTTP fetch error: " + e);
            }
        }
    });

    final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button);
    binderLocalButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */);
                Log.d(TAG, "local writeToDisk returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "local binderButton error: " + e);
            }
        }
    });

    final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button);
    binderRemoteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                boolean value = mRemoteServiceConn.stub.doDiskWrite(1);
                Log.d(TAG, "remote writeToDisk #1 returned: " + value);
                value = mRemoteServiceConn.stub.doDiskWrite(2);
                Log.d(TAG, "remote writeToDisk #2 returned: " + value);
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button);
    binderOneWayButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                Log.d(TAG, "doing oneway disk write over Binder.");
                mRemoteServiceConn.stub.doDiskOneWay();
            } catch (RemoteException e) {
                Log.d(TAG, "remote binderButton error: " + e);
            }
        }
    });

    final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button);
    binderCheckButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            int policy;
            try {
                policy = mLocalServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "local service policy: " + policy);
                policy = mRemoteServiceConn.stub.getThreadPolicy();
                Log.d(TAG, "remote service policy: " + policy);
            } catch (RemoteException e) {
                Log.d(TAG, "binderCheckButton error: " + e);
            }
        }
    });

    final Button serviceDumpButton = (Button) findViewById(R.id.service_dump);
    serviceDumpButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "About to do a service dump...");
            File file = new File("/sdcard/strictmode-service-dump.txt");
            FileOutputStream output = null;
            final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy();
            try {
                StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
                output = new FileOutputStream(file);
                StrictMode.setThreadPolicy(oldPolicy);
                boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]);
                Log.d(TAG, "Dumped = " + dumped);
            } catch (IOException e) {
                Log.e(TAG, "Can't dump service", e);
            } finally {
                StrictMode.setThreadPolicy(oldPolicy);
            }
            Log.d(TAG, "Did service dump.");
        }
    });

    final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button);
    lingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(true);
        }
    });

    final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button);
    nonlingerCloseButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            closeWithLinger(false);
        }
    });

    final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button);
    leakCursorButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
            try {
                StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
                        .penaltyLog().penaltyDropBox().build());
                db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)");
                Cursor c = db.rawQuery("SELECT * FROM foo", null);
                c = null; // never close it
                Runtime.getRuntime().gc();
            } finally {
                StrictMode.setVmPolicy(oldPolicy);
            }

        }
    });

    final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write);
    final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads);
    final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network);
    final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log);
    final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog);
    final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death);
    final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox);

    View.OnClickListener changePolicy = new View.OnClickListener() {
        public void onClick(View v) {
            StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder();
            if (checkNoWrite.isChecked())
                newPolicy.detectDiskWrites();
            if (checkNoRead.isChecked())
                newPolicy.detectDiskReads();
            if (checkNoNetwork.isChecked())
                newPolicy.detectNetwork();
            if (checkPenaltyLog.isChecked())
                newPolicy.penaltyLog();
            if (checkPenaltyDialog.isChecked())
                newPolicy.penaltyDialog();
            if (checkPenaltyDeath.isChecked())
                newPolicy.penaltyDeath();
            if (checkPenaltyDropBox.isChecked())
                newPolicy.penaltyDropBox();
            StrictMode.ThreadPolicy policy = newPolicy.build();
            Log.v(TAG, "Changing policy to: " + policy);
            StrictMode.setThreadPolicy(policy);
        }
    };
    checkNoWrite.setOnClickListener(changePolicy);
    checkNoRead.setOnClickListener(changePolicy);
    checkNoNetwork.setOnClickListener(changePolicy);
    checkPenaltyLog.setOnClickListener(changePolicy);
    checkPenaltyDialog.setOnClickListener(changePolicy);
    checkPenaltyDeath.setOnClickListener(changePolicy);
    checkPenaltyDropBox.setOnClickListener(changePolicy);
}

From source file:org.mariotaku.twidere.util.net.TwidereDns.java

@NonNull
private InetAddress[] resolveInternal(String originalHost, String host, int depth) throws IOException {
    resetLog(originalHost);/*from   ww  w.j  a va  2 s .  c  o m*/
    // Return if host is an address
    final InetAddress[] fromAddressString = fromAddressString(originalHost, host);
    if (fromAddressString != null) {
        if (BuildConfig.DEBUG) {
            addLogSplit(originalHost, host, "valid ip address", depth);
            dumpLog();
        }
        return fromAddressString;
    }
    // Find from cache
    final InetAddress[] fromCache = getCached(host);
    if (fromCache != null) {
        if (BuildConfig.DEBUG) {
            addLogSplit(originalHost, host, "hit cache", depth);
            dumpLog();
        }
        return fromCache;
    }
    // Load from custom mapping
    addLogSplit(originalHost, host, "start custom mapping resolve", depth);
    final InetAddress[] fromMapping = getFromMapping(host);
    addLogSplit(originalHost, host, "end custom mapping resolve", depth);
    if (fromMapping != null) {
        putCache(originalHost, fromMapping, -1, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            dumpLog();
        }
        return fromMapping;
    }
    // Load from /etc/hosts
    addLogSplit(originalHost, host, "start /etc/hosts resolve", depth);
    final InetAddress[] fromSystemHosts = fromSystemHosts(host);
    addLogSplit(originalHost, host, "end /etc/hosts resolve", depth);
    if (fromSystemHosts != null) {
        putCache(originalHost, fromSystemHosts, 60, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            dumpLog();
        }
        return fromSystemHosts;
    }
    // Use TCP DNS Query if enabled.
    addLogSplit(originalHost, host, "start resolver resolve", depth);
    final InetAddress[] fromResolver = fromResolver(originalHost, host, depth);
    addLogSplit(originalHost, host, "end resolver resolve", depth);
    if (fromResolver != null) {
        if (BuildConfig.DEBUG) {
            dumpLog();
        }
        return fromResolver;
    }
    addLogSplit(originalHost, host, "start system default resolve", depth);
    final InetAddress[] fromDefault = InetAddress.getAllByName(host);
    addLogSplit(originalHost, host, "end system default resolve", depth);
    putCache(host, fromDefault, 0, TimeUnit.SECONDS);
    if (BuildConfig.DEBUG) {
        dumpLog();
    }
    return fromDefault;
}

From source file:com.beetle.framework.util.OtherUtil.java

/**
 * ?dns??ip?/*from  w  w  w .  j a v  a  2  s.  c  om*/
 * 
 * @param dnsip
 * @return
 */
public final static String[] getDnsIPs(String dnsip) {
    String ips[];
    try {
        InetAddress ias[] = InetAddress.getAllByName(dnsip);
        ips = new String[ias.length];
        for (int i = 0; i < ias.length; i++) {
            ips[i] = ias[i].getHostAddress();
            ias[i] = null;
        }
    } catch (UnknownHostException e) {
        ips = null;
    }
    return ips;
}

From source file:com.mobiperf.speedometer.measurements.PingTask.java

@Override
public MeasurementResult call() throws MeasurementError {
    PingDesc desc = (PingDesc) measurementDesc;
    try {/*from www.  j av  a  2 s . c  o  m*/
        /*
         * only select ipv4 address
         */
        InetAddress[] addrs = InetAddress.getAllByName(desc.target);

        for (InetAddress address : addrs) {
            // All ping methods ping against targetIp rather than desc.target
            targetIp = address.getHostAddress();
            if (PingTask.isValidIpv4(targetIp)) {
                break;
            }

        }
        if (!PingTask.isValidIpv4(targetIp)) {
            throw new MeasurementError("No Ipv4 address for host" + desc.target);
        }

    } catch (UnknownHostException e) {
        throw new MeasurementError("Unknown host " + desc.target);
    }

    try {
        Logger.i("running ping command");
        /*
         * Prevents the phone from going to low-power mode where WiFi turns off
         */
        return executePingCmdTask();
    } catch (MeasurementError e) {
        try {
            Logger.i("running java ping");
            return executeJavaPingTask();
        } catch (MeasurementError ee) {
            Logger.i("running http ping");
            return executeHttpPingTask();
        }
    }
}

From source file:com.mindprotectionkit.freephone.signaling.SignalingSocket.java

private Socket timeoutHackConnect(SSLSocketFactory sslSocketFactory, String host, int port) throws IOException {
    InetAddress[] addresses = InetAddress.getAllByName(host);
    Socket stagedSocket = LowLatencySocketConnector.connect(addresses, port);

    Log.w("SignalingSocket", "Connected to: " + stagedSocket.getInetAddress().getHostAddress());

    SocketConnectMonitor monitor = new SocketConnectMonitor(stagedSocket);

    monitor.start();//from   w  w  w.jav a 2  s. c o  m

    Socket result = sslSocketFactory.createSocket(stagedSocket, host, port, true);

    synchronized (this) {
        this.connectionAttemptComplete = true;
        notify();

        if (result.isConnected())
            return result;
        else
            throw new IOException("Socket timed out before " + "connection completed.");
    }
}

From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java

private String query(String request) throws QueryFailedException, HttpError {
    InetAddress ips[];/* w  w  w . jav a 2 s .c  om*/
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryFailedException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            Log.d(Constants.TAG, "hkp keyserver query: " + url);
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryFailedException("querying server(s) for '" + mHost + "' failed");
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];//from www.  java2  s . c o m
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            Log.d(Constants.TAG, "hkp keyserver query: " + url);
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override//from  w  ww. j ava 2  s.  com
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private InetAddress[] resolveInternal(String originalHost, String host) throws IOException {
    if (isValidIpAddress(host))
        return fromAddressString(originalHost, host);
    // First, I'll try to load address cached.
    if (mHostCache.containsKey(host)) {
        final InetAddress[] hostAddr = mHostCache.get(host);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got cached " + Arrays.toString(hostAddr));
        }//  ww  w.ja v  a 2  s  .c  o  m
        return hostAddr;
    }
    // Then I'll try to load from custom host mapping.
    // Stupid way to find top domain, but really fast.
    if (mHostMapping.contains(host)) {
        final String mappedAddr = mHostMapping.getString(host, null);
        if (mappedAddr != null) {
            final InetAddress[] hostAddr = fromAddressString(originalHost, mappedAddr);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Got mapped " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
    }
    mSystemHosts.reloadIfNeeded();
    if (mSystemHosts.contains(host)) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, mSystemHosts.getAddress(host));
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got hosts " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    final String customMappedHost = findHost(host);
    if (customMappedHost != null) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, customMappedHost);
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + customMappedHost + " for host " + host);
        }
        return hostAddr;
    }
    // Use TCP DNS Query if enabled.
    final Resolver dns = getResolver();
    if (dns != null && mPreferences.getBoolean(KEY_TCP_DNS_QUERY, false)) {
        final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
        final Record[] records;
        lookup.setResolver(dns);
        lookup.run();
        final int result = lookup.getResult();
        if (result != Lookup.SUCCESSFUL) {
            throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
        }
        records = lookup.getAnswers();
        final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
        // Test each IP address resolved.
        for (final Record record : records) {
            if (record instanceof ARecord) {
                final InetAddress ipv4Addr = ((ARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
            } else if (record instanceof AAAARecord) {
                final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
            }
        }
        if (!resolvedAddresses.isEmpty()) {
            final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
        // No address is reachable, but I believe the IP is correct.

        for (final Record record : records) {
            if (record instanceof CNAMERecord)
                return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString());
        }
    }
    if (Utils.isDebugBuild()) {
        Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host");
    }
    final InetAddress[] defaultAddresses = InetAddress.getAllByName(host);
    mHostCache.put(host, defaultAddresses);
    return defaultAddresses;
}