Java android PING для ip и порта [дубликат]

Чтобы получить определенную часть итерабельного (например, списка), вот пример:

variable[number1:number2]

В этом примере положительное число для числа 1 - сколько компонентов вы снимаете с фронт. Отрицательное число - это полная противоположность, сколько вы держите от конца. Положительное число для числа 2 указывает, сколько компонентов вы намерены сохранить с самого начала, а отрицательным является то, сколько вы намерены взлететь с конца. Это несколько противоречит интуитивному, но вы правы, полагая, что нарезка списка чрезвычайно полезна.

47
задан swiftBoy 10 July 2012 в 19:21
поделиться

9 ответов

Используйте этот код: этот метод работает с 4.3+, а также для версий ниже.

   try {

         Process process = null;

        if(Build.VERSION.SDK_INT <= 16) {
            // shiny APIS 
               process = Runtime.getRuntime().exec(
                    "/system/bin/ping -w 1 -c 1 " + url);


        } 
        else 
        {

                   process = new ProcessBuilder()
                 .command("/system/bin/ping", url)
                 .redirectErrorStream(true)
                 .start();

            }



        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));

        StringBuffer output = new StringBuffer();
        String temp;

        while ( (temp = reader.readLine()) != null)//.read(buffer)) > 0)
        {
            output.append(temp);
            count++;
        }

        reader.close();


        if(count > 0)
            str = output.toString();

        process.destroy();
     } catch (IOException e) {
         e.printStackTrace();
    }

    Log.i("PING Count", ""+count);
    Log.i("PING String", str);
-1
ответ дан Ahmad Arslan 27 August 2018 в 22:33
поделиться

Я пробовал следующий код, который работает для меня.

private boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue "+mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }
        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;
    }
47
ответ дан Al Lelopath 27 August 2018 в 22:33
поделиться

Это простой ping, который я использую в одном из проектов:

public static class Ping {
    public String net = "NO_CONNECTION";
    public String host;
    public String ip;
    public int dns = Integer.MAX_VALUE;
    public int cnt = Integer.MAX_VALUE;
}

public static Ping ping(URL url, Context ctx) {
    Ping r = new Ping();
    if (isNetworkConnected(ctx)) {
        r.net = getNetworkType(ctx);
        try {
            String hostAddress;
            long start = System.currentTimeMillis();
            hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
            long dnsResolved = System.currentTimeMillis();
            Socket socket = new Socket(hostAddress, url.getPort());
            socket.close();
            long probeFinish = System.currentTimeMillis();
            r.dns = (int) (dnsResolved - start);
            r.cnt = (int) (probeFinish - dnsResolved);
            r.host = url.getHost();
            r.ip = hostAddress;
        }
        catch (Exception ex) {
            Timber.e("Unable to ping");
        }
    }
    return r;
}

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

@Nullable
public static String getNetworkType(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        return activeNetwork.getTypeName();
    }
    return null;
}

Использование: ping(new URL("https://www.google.com:443/"), this);

Результат: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}

6
ответ дан Alexander Mayatsky 27 August 2018 в 22:33
поделиться

Запустите утилиту ping в команде Android и выполните синтаксический анализ (при условии, что у вас есть права на root)

См. следующий фрагмент кода Java:

executeCmd("ping -c 1 -w 1 google.com", false);

public static String executeCmd(String cmd, boolean sudo){
    try {

        Process p;
        if(!sudo)
            p= Runtime.getRuntime().exec(cmd);
        else{
            p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String s;
        String res = "";
        while ((s = stdInput.readLine()) != null) {
            res += s + "\n";
        }
        p.destroy();
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";

}
11
ответ дан Dylan Knowles 27 August 2018 в 22:33
поделиться

В моем случае ping работает с устройства, но не с эмулятора. Я нашел эту документацию: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking

По теме «Ограничения локальной сети» говорит:

«В зависимости от среды эмулятор может не поддерживать другие протоколы (например, ICMP, используемый для« ping »), возможно, не поддерживается. В настоящее время эмулятор не поддерживает поддержка IGMP или многоадресной рассылки. "

Дополнительная информация: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297

это известное ограничение сетевого стека QEMU в пользовательском режиме. Цитата из исходного документа: Обратите внимание, что ping не надежно поддерживается в Интернете, поскольку для этого потребуются привилегии root. Это означает, что вы можете только пинговать локальный маршрутизатор (10.0.2.2).

7
ответ дан Eugene van der Merwe 27 August 2018 в 22:33
поделиться

Возможно, ICMP-пакеты заблокированы вашим (мобильным) провайдером. Если этот код не работает на эмуляторе, попробуйте обнюхивать через wirehark или любого другого сниффера и посмотреть, что происходит на проводе, когда вы запускаете метод isReachable ().

Вы также можете найти информацию в журнале устройства.

1
ответ дан Luminger 27 August 2018 в 22:33
поделиться

Ping для сервера google или любого другого сервера

public boolean isConecctedToInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }
    return false;
}
3
ответ дан Pawan Kumar Baranwal 27 August 2018 в 22:33
поделиться

это сработало для меня, без корня, Android 6.0, Android Studio, Acatel U3:

    private boolean Ping(String IP){
    System.out.println("executeCommand");
    Runtime runtime = Runtime.getRuntime();
    try
    {
        Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 " + IP);
        int mExitValue = mIpAddrProcess.waitFor();
        System.out.println(" mExitValue "+mExitValue);
        if(mExitValue==0){
            return true;
        }else{
            return false;
        }
    }
    catch (InterruptedException ignore)
    {
        ignore.printStackTrace();
        System.out.println(" Exception:"+ignore);
    }
    catch (IOException e)
    {
        e.printStackTrace();
        System.out.println(" Exception:"+e);
    }
    return false;
}
0
ответ дан Ramon Black 27 August 2018 в 22:33
поделиться

Это то, что я реализовал сам, который возвращает среднюю задержку:

/*
Returns the latency to a given server in mili-seconds by issuing a ping command.
system will issue NUMBER_OF_PACKTETS ICMP Echo Request packet each having size of 56 bytes
every second, and returns the avg latency of them.
Returns 0 when there is no connection
 */
public double getLatency(String ipAddress){
    String pingCommand = "/system/bin/ping -c " + NUMBER_OF_PACKTETS + " " + ipAddress;
    String inputLine = "";
    double avgRtt = 0;

    try {
        // execute the command on the environment interface
        Process process = Runtime.getRuntime().exec(pingCommand);
        // gets the input stream to get the output of the executed command
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        inputLine = bufferedReader.readLine();
        while ((inputLine != null)) {
            if (inputLine.length() > 0 && inputLine.contains("avg")) {  // when we get to the last line of executed ping command
                break;
            }
            inputLine = bufferedReader.readLine();
        }
    }
    catch (IOException e){
        Log.v(DEBUG_TAG, "getLatency: EXCEPTION");
        e.printStackTrace();
    }

    // Extracting the average round trip time from the inputLine string
    String afterEqual = inputLine.substring(inputLine.indexOf("="), inputLine.length()).trim();
    String afterFirstSlash = afterEqual.substring(afterEqual.indexOf('/') + 1, afterEqual.length()).trim();
    String strAvgRtt = afterFirstSlash.substring(0, afterFirstSlash.indexOf('/'));
    avgRtt = Double.valueOf(strAvgRtt);

    return avgRtt;
}
1
ответ дан sorry_I_wont 27 August 2018 в 22:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: