`
hewei870723
  • 浏览: 62860 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

转载 java ping功能

阅读更多
一、纯Java实现ICMP的ping命令
import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.*;
import java.util.regex.*;
public class Ping {
    static int DAYTIME_PORT = 13;
    static int port = DAYTIME_PORT;
    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;
        }
    }
    static class Printer extends Thread {
        LinkedList 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;
            }
        }
    }
    static class Connector extends Thread {
        Selector sel;
        Printer printer;
        LinkedList pending = new LinkedList();
        Connector(Printer pr) throws IOException {
            printer = pr;
            sel = Selector.open();
            setName("Connector");
        }
        void add(Target t) {
            SocketChannel sc = null;
            try {
                sc = SocketChannel.open();
                sc.configureBlocking(false);
                boolean connected = sc.connect(t.address);
                t.channel = sc;
                t.connectStart = System.currentTimeMillis();
                if (connected) {
                    t.connectFinish = t.connectStart;
                    sc.close();
                    printer.add(t);
                } else {
                    synchronized (pending) {
                        pending.add(t);
                    }
                    sel.wakeup();
                }
            } catch (IOException x) {
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (IOException xx) {
                    }
                }
                t.failure = x;
                printer.add(t);
            }
        }
        void processPendingTargets() throws IOException {
            synchronized (pending) {
                while (pending.size() > 0) {
                    Target t = (Target) pending.removeFirst();
                    try {
                        t.channel.register(sel, SelectionKey.OP_CONNECT, t);
                    } catch (IOException x) {
                        t.channel.close();
                        t.failure = x;
                        printer.add(t);
                    }
                }
            }
        }
        void processSelectedKeys() throws IOException {
            for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();) {
                SelectionKey sk = (SelectionKey) i.next();
                i.remove();
                Target t = (Target) sk.attachment();
                SocketChannel sc = (SocketChannel) sk.channel();
                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;
        void shutdown() {
            shutdown = true;
            sel.wakeup();
        }
        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 {
        args = new String[] { "8888", "192.168.10.193" };
        if (args.length < 1) {
            System.err.println("Usage: java Ping [port] host...");
            return;
        }
        int firstArg = 0;
        if (Pattern.matches("[0-9]+", args[0])) {
            port = Integer.parseInt(args[0]);
            firstArg = 1;
        }
        Printer printer = new Printer();
        printer.start();
        Connector connector = new Connector(printer);
        connector.start();
        LinkedList targets = new LinkedList();
        for (int i = firstArg; i < args.length; i++) {
            Target t = new Target(args[i]);
            targets.add(t);
            connector.add(t);
        }
        Thread.sleep(2000);
        connector.shutdown();
        connector.join();
        for (Iterator i = targets.iterator(); i.hasNext();) {
            Target t = (Target) i.next();
            if (!t.shown)
                t.show();
        }
    }
}
二、JAVA调用外部EXE实现PING功能
import java.io.*;
import java.lang.*;

public class Ping {
   
   
    public Ping() {
    }
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("syntax Error!");
        }
        else
        {
            String line = null;
            try
            {
                Process pro = Runtime.getRuntime().exec("ping " + args[0]);
                BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
                while((line = buf.readLine()) != null)
                    System.out.println(line);
            }
            catch(Exception ex)
            {
                System.out.println(ex.getMessage());
            }
        }
       
    }
}
三、ICMP Ping in Java(JDK 1.5 and above)
Programatically using ICMP Ping is a great way to establish that a server is up and running. Previously you couldn't do ICMP ping (what ping command does in Linux/Unix & Windows) in java without using JNI or exec calls. Here is a simple and reliable method to do ICMP pings in Java without using JNI or NIO.

String host = "172.16.0.2"
int timeOut = 3000; // I recommend 3 seconds at least
boolean status = InetAddress.getByName(host).isReachable(timeOut)

status is true if the machine is reachable by ping; false otherwise. Best effort is made to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
In Linux/Unix you may have to suid the java executable to get ICMP Ping working, ECHO REQUESTs will be fine even without suid. However on Windows you can get ICMP Ping without any issues whatsoever.
四、最简单的办法,直接调用CMD
   try
        {
         Runtime.getRuntime().exec("cmd /c start ping 127.0.0.1");
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
ping的过程可以显示在本地的办法
import java.io.*;
public class Ping
{
    public static void main(String args[])
    {
        String line = null;
        try
        {
            Process pro = Runtime.getRuntime().exec("ping 127.0.0.1 ");
            BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            while ((line = buf.readLine()) != null)
                System.out.println(line);
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}
五、模拟PING
    利用InetAddress的isReachable方法可以实现ping的功能,里面参数设定超时时间,返回结果表示是否连上
try {
            InetAddress address = InetAddress.getByName("192.168.0.113");
            System.out.println(address.isReachable(5000));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
六、模拟TELNET
    利用Socket的connect(SocketAddress endpoint, int timeout)方法可以实现telnet的功能,如果catch到异常说明telnet失败
  try  {
           Socket server = new Socket();
           InetSocketAddress address = new InetSocketAddress("192.168.0.113",
                    8080);
           server.connect(address, 5000);
           server.close();
        } catch (UnknownHostException e){
            System.out.println("telnet失败");
        } catch (IOException e){
            System.out.println("telnet失败");
        }
分享到:
评论

相关推荐

    Java实现ping功能

    这个项目名为"Java实现ping功能",它利用Java编程语言,结合Spring Boot、Thymeleaf和Maven等技术,实现了类似操作系统内置ping命令的功能,并且增加了端口检测的特性。下面我们将详细探讨这一项目中的关键知识点。 ...

    java中ping命令ping工具类(循环ping)

    java中ping命令ping工具类(循环ping) java ping ip ping命令 ping工具类 支持linux和windows等所有平台 Ping是Windows下的一个命令 在Unix和Linux下也有这个命令。 ping也属于一个通信协议,是TCP/IP协议的一部分 ...

    java实现的模拟ping功能

    ### Java实现的模拟Ping功能详解 #### 一、概述 在计算机网络中,Ping命令是一种常用的测试工具,用于检查网络连接是否可用,并测量与远程主机的往返时间。本篇文章将详细解析一个用Java语言编写的模拟Ping功能的...

    用java实现ping的几种方式

    本文将介绍几种使用Java来实现`ping`功能的方法。 #### 方法一:纯Java实现ICMP的ping命令 在Java中,可以不依赖于操作系统提供的`ping`命令或任何其他外部工具,通过编程的方式直接发送ICMP包来实现`ping`功能。...

    用java实现ping功能

    在Java编程中,我们不能直接使用内置的库来实现ping功能,因为Java标准库并不包含这样的功能。但是,我们可以借助第三方库如jpcap(Java Packet Capture)来实现这个功能。 jpcap是一个Java库,它提供了对网络接口...

    javaping.rar_JAVA ping_ping_ping(java)

    这个"javaping.rar"压缩包包含了一个Java实现的ping功能,使得开发者能够在Java应用程序中集成网络检测的能力。下面将详细探讨Java如何实现ping操作以及其背后的原理。 首先,我们要理解原始的ping命令是基于ICMP...

    udp_Ping_JAVAping_javaudpping_java_基于UDP的PING_udp_Ping_

    UDP(User Datagram Protocol)是一种无...在给定的项目“udp_Ping_JAVAping_javaudpping_java_基于UDP的PING_udp_Ping”中,你可以找到实现这些功能的具体代码,进一步学习和理解Java如何操作UDP套接字进行数据通信。

    TCP-Ping_ping_TCP,IP_JAVAping_java_源码.zip

    在上述代码中,`TCP-Ping_ping_TCP,IP_JAVAping_java_源码.zip`可能包含了实现这些功能的完整Java源代码。解压这个压缩包后,你可以学习和研究如何在实际项目中使用这些代码来实现TCP-Ping功能。这不仅可以帮助你...

    java语言实现ping函数的功能

    在Java编程语言中,实现ping功能通常涉及到网络通信和套接字编程。ping命令在网络中主要用于检查网络连接的可达性,其工作原理是发送ICMP(Internet Control Message Protocol)回显请求报文到目标主机,然后接收...

    JPing:适用于Java的ICMP Ping实用程序

    Java Ping概述这是一个简单的工具,可让您查看是否可以通过ICMP ping而不是Java随附的TCP方法访问远程计算机: InetAddress . getByName(ip) . isReachable(timeout); 在某些Windows机器上的实例中,我注意到使用...

    实现linux java ping 及traceroute 功能.rar

    本文将详细解析如何在Linux环境中利用Java语言实现`ping`和`traceroute`的功能,并结合C#的相关知识进行探讨。 首先,`ping`是一个简单但实用的网络工具,用于测试主机之间是否可达以及网络的延迟时间。在Linux中,...

    java ping程序

    在Java中,由于标准库并不直接支持ICMP协议,因此实现ping功能需要模拟 ICMP Echo 请求。这通常涉及到构造特定的字节序列,这些序列在原始的IP头部和ICMP头部之后。ICMP头部通常包括类型、代码和校验和字段,对于...

    java实现ping.pdf

    在描述中,“java实现ping.pdf”重申了文档的主题,强调了该程序的功能:用Java语言编写网络诊断工具。同时,通过提及“技术及资料”,揭示了文档可能包含程序源代码、相关技术细节或使用说明。 根据提供的部分源...

    基于socket实现Ping功能的源代码

    本文将深入探讨基于Socket实现Ping功能的源代码,涉及到的主要知识点包括Socket编程、原始套接字(SOCK_RAW)以及ICMP(Internet Control Message Protocol)协议。 首先,我们需要理解什么是Socket。Socket是操作...

    java定时ping命令程序

    除了`java.util.Timer`和`java.util.TimerTask`,Java 5及更高版本还提供了`java.concurrent.ScheduledExecutorService`接口,它提供了更灵活的定时任务调度功能。你可以根据项目需求选择适合的定时任务实现方式。 ...

    基于Java实现PING的服务器端和客户端设计.zip

    资源包含:课程报告word+源码 编程实现PING的服务器端和客户端,实现操作系统提供的ping命令的类似功能。详细介绍参考:https://blog.csdn.net/sheziqiong/article/details/127039936

    java 实现的 ping程序

    在Java中实现ping功能,我们需要使用Java的Socket编程接口,但由于Java标准库并不直接支持ICMP协议,我们需要使用更低级别的套接字API,如`java.net.Socket`或`java.net.DatagramSocket`。一般情况下,我们会通过...

    TCP-Ping_ping_TCP,IP_JAVAping_java.zip

    6. **命令行参数解析**:TCP-Ping可能接受命令行参数,如目标IP、端口、次数等,这需要解析命令行参数,Java的`java.util.argv`和`java.util.Properties`类可以实现这一功能。 7. **结果输出**:TCP-Ping的结果通常...

    实现linux java ping 及traceroute 功能.zip

    首先,让我们看看如何在Java中实现`ping`功能。在Java中,我们可以利用`java.net.Socket`类或`java.net.InetAddress`类来创建一个网络连接并检查其连通性。以下是一个简单的示例: ```java import java.io....

Global site tag (gtag.js) - Google Analytics