如何使用套接字ping IP并通过它发送数据?

如何使用套接字程序ping IP地址并通过它发送数据?

你不能用Java做ping – ping工作在ICMP级别,它在IP之上工作,而Java提供对UDP(位于IP之上)和TCP(再次在IP之上)的支持。 它基本上是一个不同的(更高级别)协议,您需要编写自己的(本机)库才能访问IP堆栈。

Ping是一种特定的ICMP协议。 您无法使用纯Java发送ICMP数据包。

但是,您可以打开特定端口的TCP套接字并向其发送一些数据。 有数百万个关于如何做到这一点的教程示例。

我建议你看看这些

http://www.google.co.uk/search?q=java+socket+tutorial 600万结果

http://www.google.co.uk/search?q=java+socket+example 1160万条结果。

要发送一个字符,你可以做

Socket s = new Socket(hostname, port); s.getOutputStream().write((byte) '\n'); int ch = s.getInputStream().read(); s.close(); if (ch == '\n') // its all good. 

Ping使用java中不可用的ICMP协议。 这可以是在java中ping服务器的更好方法:

  try{ String s = null; List commands = new ArrayList(); commands.add("ping"); commands.add("192.168.2.154"); ProcessBuilder processbuilder = new ProcessBuilder(commands); Process process = processbuilder.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } }catch (Exception e) { System.out.println("This is sad "); 

}

另一种方法是使用纯Java套接字。