Java 如何ping一个IP地址
我正在使用这部分代码在java中ping一个ip地址,但只有ping localhost成功,对于其他主机,程序说无法访问该主机。 我禁用了防火墙,但仍然存在此问题Java 如何ping一个IP地址,java,ping,host,Java,Ping,Host,我正在使用这部分代码在java中ping一个ip地址,但只有ping localhost成功,对于其他主机,程序说无法访问该主机。 我禁用了防火墙,但仍然存在此问题 public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = "127.0.0.1"; InetAddress inet = InetAddress.getByName(ipAd
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");
}
输出为:
向127.0.0.1发送Ping请求可以访问主机
正在向173.194.32.38发送Ping请求
无法访问主机
检查您的连接。在我的计算机上,这两个IP都可以访问: 向127.0.0.1发送Ping请求
可以访问主机
正在向173.194.32.38发送Ping请求
主机是可访问的 编辑: 您可以尝试修改代码以使用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()方法可能会尝试某种在您的计算机上不可能进行的反向DNS查找,getByAddress()可能会绕过这一点。您不能简单地在Java中ping,因为它依赖于ICMP,遗憾的是Java中不支持ICMP 改用插座
希望对您有所帮助
InetAddress.isReachable()
根据:
“。如果
无法获得特权,否则将尝试建立TCP
目标主机的端口7(Echo)上的连接..”
选项1(ICMP)通常需要管理权限 它肯定会有用的
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);
}
}
}
import java.io.*;
导入java.util.*;
公共类JavapingExample程序
{
公共静态void main(字符串参数[])
抛出IOException
{
//将ping命令创建为字符串列表
JavaPingExampleProgram ping=新的JavaPingExampleProgram();
List命令=new ArrayList();
命令。添加(“ping”);
命令。添加(“-c”);
命令。添加(“5”);
命令。添加(“74.125.236.73”);
ping.docomand(命令);
}
公共无效doCommand(列表命令)
抛出IOException
{
字符串s=null;
ProcessBuilder pb=新的ProcessBuilder(命令);
Process进程=pb.start();
BufferedReader stdInput=新的BufferedReader(新的InputStreamReader(process.getInputStream());
BufferedReader stdError=新的BufferedReader(新的InputStreamReader(process.getErrorStream());
//读取命令的输出
System.out.println(“这是命令的标准输出:\n”);
而((s=stdInput.readLine())!=null)
{
系统输出打印项次;
}
//从尝试的命令中读取任何错误
System.out.println(“这是命令的标准错误(如果有):\n”);
而((s=stdError.readLine())!=null)
{
系统输出打印项次;
}
}
}
您可以使用此方法ping Windows和其他平台上的主机:
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;
}
在使用oracle jdk的linux上,OP提交的代码在非root时使用端口7,在root时使用ICMP。当以root用户身份运行时,它确实会执行一个真正的ICMP回显请求,如文档所指定
如果您在MS计算机上运行此应用程序,您可能必须以管理员身份运行此应用程序才能获得ICMP行为。我知道前面的条目已经回答了这一问题,但对于其他任何遇到此问题的人,我确实找到了一种不需要在windows中使用“ping”过程然后清除输出的方法 我所做的是使用JNA调用Window的IP helper库来执行ICMP回显
请参见我认为此代码将帮助您:
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();
}
}
}
这只是对其他人给出的代码的一个补充,即使它们工作得很好,但在某些情况下,如果internet运行缓慢或存在未知的网络问题,某些代码将无法工作(
isReachable()
)。但是下面提到的代码创建了一个进程,充当windows的命令行ping(cmd ping)。它在任何情况下都适用于我,经过尝试和测试
代码:-
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);
}
}
希望有帮助,干杯 以下是在
Java
中ping IP地址的方法,该方法应适用于Windows
和Unix
系统:
import org.apache.commons.lang3.SystemUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CommandLine
{
/**
* @param ipAddress The internet protocol address to ping
* @return True if the address is responsive, false otherwise
*/
public static boolean isReachable(String ipAddress) throws IOException
{
List<String> command = buildCommand(ipAddress);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
try (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;
}
private static List<String> buildCommand(String ipAddress)
{
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(ipAddress);
return command;
}
}
import org.apache.commons.lang3.SystemUtils;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.List;
公共类命令行
{
/**
*@param ipAddress将internet协议地址发送到ping
*@如果地址有响应,则返回True,否则返回false
*/
公共静态布尔值IsRecable(字符串ipAddress)引发IOException
{
列表命令=buildCommand(ipAddress);
ProcessBuilder ProcessBuilder=新的ProcessBuilder(命令);
Process=processBuilder.start();
try(BufferedReader standardOutput=new BufferedReader(new InputStreamReader(process.getInputStream()))
{
字符串输出线;
而((outputLine=standardOutput.readLine())!=null)
{
//拾取Windows和Unix无法访问的主机
if(outputLine.toLowerCase().contains(“目标主机不可访问”))
{
返回false;
}
}
}
返回true;
}
私有静态列表构建命令(字符串ipAddress)
{
List命令=new ArrayList();
命令。添加(“ping”);
if(SystemUtils.IS\u OS\u WINDOWS)
{
添加(“-n”);
}else if(SystemUtils.IS\u OS\u UNIX)
{
添加(“-c”);
}否则
{
抛出新的UnsupportedOperationException(“不支持的操作系统”);
}
命令。添加(“1”);
添加命令(ipAddress);
返回命令;
}
}
确保添加到依赖项中。这应该可以:
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";
}
}InetAddress并不总是返回正确的值。对于本地主机,这是成功的,但对于其他主机,这表明无法访问该主机。尝试使用ping命令,如下所示
try {
String cmd = "cmd /C ping -n 1 " + ip + " | find \"TTL\"";
Process myProcess = Runtime.getRuntime().exec(cmd);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
}
else {
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
尽管这不依赖于Windows上的ICMP,但此实现在
public static Duration ping(String host) {
Instant startTime = Instant.now();
try {
InetAddress address = InetAddress.getByName(host);
if (address.isReachable(1000)) {
return Duration.between(startTime, Instant.now());
}
} catch (IOException e) {
// Host not available, nothing to do here
}
return Duration.ofDays(1);
}
URL siteURL = new URL(url);
connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(pingTime);
connection.connect();
code = connection.getResponseCode();
if (code == 200) {
code = 200;
}.
public int pingBat(Network network) {
ProcessBuilder pb = new ProcessBuilder(pingBatLocation);
Map<String, String> env = pb.environment();
env.put(
"echoCount", noOfPings + "");
env.put(
"pingIp", pingIp);
File outputFile = new File(outputFileLocation);
File errorFile = new File(errorFileLocation);
pb.redirectOutput(outputFile);
pb.redirectError(errorFile);
Process process;
try {
process = pb.start();
process.waitFor();
String finalOutput = printFile(outputFile);
if (finalOutput != null && finalOutput.toLowerCase().contains("reply from")) {
return 200;
} else {
return 202;
}
} catch (IOException e) {
log.debug(e.getMessage());
return 203;
} catch (InterruptedException e) {
log.debug(e.getMessage());
return 204;
}