如何ping一个IP地址

我正在使用这部分代码在java中ping一个ip地址,但只ping本地主机是成功的和其他主机程序说,主机是无法访问。 我禁用了防火墙,但仍然有这个问题

public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = "127.0.0.1"; InetAddress inet = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); ipAddress = "173.194.32.38"; inet = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); } 

输出是:

发送Ping请求到127.0.0.1
主机是可达的
发送Ping请求到173.194.32.38
主机不可访问

你不能简单地使用Java平台,因为它依赖于ICMP,这在Java中是不被支持的

http://mindprod.com/jgloss/ping.html

改用套接字

希望它有帮助

InetAddress.isReachable()根据javadoc :

“一个典型的实现将使用ICMP ECHO REQUESTs,如果可以获得特权,否则它将尝试在目标主机的端口7(Echo)上build立一个TCP连接。

选项#1(ICMP)通常需要pipe理(root)权限。

检查您的连接。 在我的电脑上,这两个IP的打印REACHABLE:

发送Ping请求到127.0.0.1
主机是可达的
发送Ping请求到173.194.32.38
主机是可达的

编辑:

您可以尝试修改代码以使用getByAddress()来获取地址:

 public static void main(String[] args) throws UnknownHostException, IOException { InetAddress inet; inet = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); System.out.println("Sending Ping Request to " + inet); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); inet = InetAddress.getByAddress(new byte[] { (byte) 173, (byte) 194, 32, 38 }); System.out.println("Sending Ping Request to " + inet); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); } 

getByName()方法可能会尝试某种forms的反向DNS查找,这可能无法在您的计算机上执行,getByAddress()可能会绕过该查询。

我认为这个代码将帮助你:

 public class PingExample { public static void main(String[] args){ try{ InetAddress address = InetAddress.getByName("192.168.1.103"); boolean reachable = address.isReachable(10000); System.out.println("Is host reachable? " + reachable); } catch (Exception e){ e.printStackTrace(); } } } 

这将工作肯定

 import java.io.*; import java.util.*; public class JavaPingExampleProgram { public static void main(String args[]) throws IOException { // create the ping command as a list of strings JavaPingExampleProgram ping = new JavaPingExampleProgram(); List<String> commands = new ArrayList<String>(); commands.add("ping"); commands.add("-c"); commands.add("5"); commands.add("74.125.236.73"); ping.doCommand(commands); } public void doCommand(List<String> command) throws IOException { String s = null; ProcessBuilder pb = new ProcessBuilder(command); Process process = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); // read the output from the command System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } } } 

您可以使用此方法在Windows或其他平台上ping主机:

 private static boolean ping(String host) throws IOException, InterruptedException { boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win"); ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", host); Process proc = processBuilder.start(); int returnVal = proc.waitFor(); return returnVal == 0; } 

只是增加了别人给的东西,即使它们工作的很好,但是在某些情况下,如果互联网速度慢,或者存在一些未知的networking问题,一些代码将不起作用( isReachable() )。 但是下面提到的这个代码创build了一个作为命令行ping(cmd ping)到windows的进程。 它在任何情况下都适用于我,经过testing。

代码: –

 public class JavaPingApp { public static void runSystemCommand(String command) { try { Process p = Runtime.getRuntime().exec(command); BufferedReader inputStream = new BufferedReader( new InputStreamReader(p.getInputStream())); String s = ""; // reading output stream of the command while ((s = inputStream.readLine()) != null) { System.out.println(s); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String ip = "stackoverflow.com"; //Any IP Address on your network / Web runSystemCommand("ping " + ip); } } 

希望它有帮助,干杯!

在使用oracle-jdk的linux上,OP提交的代码使用的是非root和ICMP时的端口7。 它以文档指定的超级用户身份运行时会执行真正的ICMP回显请求。

如果您在MS机器上运行此应用程序,则可能必须以pipe理员身份运行该应用程序以获取ICMP行为。

下面是一个在Java和Windows系统下工作的IP地址的方法:

 import org.apache.commons.lang.SystemUtils; import java.io.*; import java.util.*; public class CommandLine { /** * @param internetProtocolAddress The internet protocol address to ping * @return True if the address is responsive, false otherwise * @throws IOException */ public static boolean isReachable(String internetProtocolAddress) throws IOException { List<String> command = new ArrayList<>(); command.add("ping"); if (SystemUtils.IS_OS_WINDOWS) { command.add("-n"); } else if (SystemUtils.IS_OS_UNIX) { command.add("-c"); } else { throw new UnsupportedOperationException("Unsupported operating system"); } command.add("1"); command.add(internetProtocolAddress); ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = processBuilder.start(); BufferedReader standardOutput = new BufferedReader(new InputStreamReader(process.getInputStream())); String outputLine; while ((outputLine = standardOutput.readLine()) != null) { // Picks up Windows and Unix unreachable hosts if (outputLine.toLowerCase().contains("destination host unreachable")) { return false; } } return true; } } 

确保将Apache Commons Lang添加到您的pom.xml文件中。

我知道这已经回答了以前的条目,但对于这个问题的任何其他人,我确实find了一种方法,不需要在Windows中使用“ping”过程,然后清理输出。

我所做的就是使用JNA来调用Window的IP帮助程序库来执行ICMP回显

看到我自己的答案,我自己的类似问题

这应该工作:

 import java.io.BufferedReader; import java.io.InputStreamReader; public class Pinger { private static String keyWordTolookFor = "average"; public Pinger() { // TODO Auto-generated constructor stub } public static void main(String[] args) { //Test the ping method on Windows. System.out.println(ping("192.168.0.1")); } public String ping(String IP) { try { String line; Process p = Runtime.getRuntime().exec("ping -n 1 " + IP); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while (((line = input.readLine()) != null)) { if (line.toLowerCase().indexOf(keyWordTolookFor.toLowerCase()) != -1) { String delims = "[ ]+"; String[] tokens = line.split(delims); return tokens[tokens.length - 1]; } } input.close(); } catch (Exception err) { err.printStackTrace(); } return "Offline"; } 

}