1

I want to get the delay time between 2 PC by this way:

currentTime = System.currentTimeMillis();           
isPinged = InetAddress.getByName("192.168.6.18").isReachable(2000);                 
currentTime = System.currentTimeMillis() - currentTime;
System.out.println("----"+isPinged+":"+currentTime);

but the results always be "false" except "localhost",I tried change the getByName("192.168.6.18") to the PC of LAN ,or the website like "www.facebook.com",but it has no effect

4

1 回答 1

-3

将此方法用于 Windows PC

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public Boolean ping(String ipaddress)
{
    Runtime runtime = Runtime.getRuntime();
    String cmds = "ping "+ipaddress;
    System.out.println(cmds);
    Process proc;
    try {
         proc = runtime.exec(cmds);
        proc.getOutputStream().close();
        InputStream inputstream = proc.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            if(line.contains("Reply from "+ipaddress+":"))
                {
                return true;    
                }
            }
        }catch (IOException e) {
    e.printStackTrace();
    }
    return false;
 }

有关更多详细信息,请参阅Ping 类

对于 Windows 以外的 PC 使用

  public Boolean IsReachable(String ipaddress) {
    try {            
        final InetAddress host = InetAddress.getByName(ipaddress);

        try {
            return host.isReachable(3000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return false;
}
于 2014-04-06T18:25:20.747 回答