一、纯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失败");
}
分享到:
相关推荐
此项目是spring boot+thymeleaf+maven的Java实现ping命令的功能以及端口检测是否开放的功能
java调用jpcap实现ping功能代码
很好的一个java实现的ping功能,适合初学者学习使用,相互学习,相互交流啊
用java实现ping的几种方式:纯Java实现ICMP的ping命令,JAVA调用外部EXE实现PING功能,ICMP Ping in Java(JDK 1.5 and above),最简单的办法,直接调用CMD
资源包含:课程报告word+源码 编程实现PING的服务器端和客户端,实现操作系统提供的ping命令的类似功能。详细介绍参考:https://blog.csdn.net/sheziqiong/article/details/127039936
Java简单实现Ping功能
一段JAVA代码 实现ping功能 import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.SocketChannel;
通过几个java包中的API实现了ping这样的功能,完整代码 请参考!
基于socket的网络编程技术,用到SOCK_RAW的原始套接字类型。里面对简单ICMP协议和IP协议有着很完整的诠释和定义。可以交流zhaquanmin@163.com
Java实现Ping功能(采用JNI技术),有源码和例子
实现linux java ping 及traceroute 功能.rar
利用原始套接字实现PING功能的源代码(13kb)
使用java来实现ping功能。 并写入文件。为了使用java来实现ping的功能,有人推荐使用java的 Runtime.exec()方法来直接调用系统的Ping命令,也有人完成了纯Java实现Ping的程序,使用的是Java的NIO包(native io,...
实现linux java ping 及traceroute 功能.zip
2.设计要求:通过原始套接字编程,模拟Ping命令,实现其基本功能,即输入一个IP地址或一段IP地址的范围,分别测试其中每个IP地址所对应主机的可达性,并返回耗时、生存时间等参数,并统计成功发送和回送的Ping报文。...
2.设计要求:通过原始套接字编程,实现Ping的基本功能 2.1初始化Windows Sockets网络环境; 2.2解析命令行参数,构造目的端socket地址; 2.3定义IP、ICMP报文; 2.4接收ICMP差错报文并进行解析。 3. Java环境为...
参考别人的源码。略有改动。ping 可以ping 域名。traceroute 不会卡在某个路径死掉。
用java图形界面实现电脑cmd界面的ping功能 //ps:没有用到ICMP协议,直接调用系统的ping功能输出到java图形界面
2.设计要求:通过原始套接字编程,模拟Ping命令,实现其基本功能,即输入一个IP地址或一段IP地址的范围,分别测试其中每个IP地址所对应主机的可达性,并返回耗时、生存时间等参数,并统计成功发送和回送的Ping报文。...
1.编程实现PING的服务器端和客户端,实现操作系统提供的ping命令的类似功能。 2.服务器端PingServer功能: 2.1 可以并发地为多个用户服务; 2.2 显示用户通过客户端发送来的消息内容(包含头部和payload); 2.3 能够...