java 模拟Ping过程,用InetSocketAddress实现

lxw886 2010-06-08 08:01:29
InetSocketAddress(InetAddress,port)
这里要Ping的主要的是交换机,所以不需要port这个参数,而port这个参数又是必须的,不知道有没有什么变通的方法
谢谢~
...全文
1234 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
only_xxp 2011-09-19
  • 打赏
  • 举报
回复
学习了
zhentengai 2010-06-09
  • 打赏
  • 举报
回复
自己重写.

把port给封装一下.

我先去试试
「已注销」 2010-06-09
  • 打赏
  • 举报
回复
mouer 2010-06-09
  • 打赏
  • 举报
回复
sun官方的,参考下吧
http://java.sun.com/j2se/1.5.0/docs/guide/nio/example/Ping.java
lxw886 2010-06-09
  • 打赏
  • 举报
回复
貌似之前也有个人讨论了这样的一个东西
帖子http://topic.csdn.net/u/20100422/11/e69924f6-d6ca-43d3-86……
[/Quote]
先谢谢了~
yueguangkai001 2010-06-09
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 lxw886 的回复:]
用这个方法是简单,但是当要求单位时间ping大量ip的话,只能通过增开线程的方法,我想通过开较少线程数来ping大量的IP,所以想到了用InetSocketAddress,继续等待高人.....
[/Quote]
貌似之前也有个人讨论了这样的一个东西
帖子http://topic.csdn.net/u/20100422/11/e69924f6-d6ca-43d3-86f4-498b9400d593.html
你去问问他有好的方案么
lxw886 2010-06-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 b11ght 的回复:]
Java code

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;


public class Ping {……
[/Quote]
你贴的这个方法就是我现在想改进的,如果说address = new InetSocketAddress(InetAddress.getByName(host),port);中port变量不输入的话程序是有错的,而ping交换机是不用port的.....
lxw886 2010-06-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 yueguangkai001 的回复:]
既然是ping就用ping来做萨

Java code

private String pingIP(String IP)
{
BufferedReader in = null;
Runtime rt = Runtime.getRuntime();
boolean FoundMatch = false;
St……
[/Quote]

用这个方法是简单,但是当要求单位时间ping大量ip的话,只能通过增开线程的方法,我想通过开较少线程数来ping大量的IP,所以想到了用InetSocketAddress,继续等待高人.....
b11ght 2010-06-09
  • 打赏
  • 举报
回复

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;


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 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 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 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();
}

}

}
氧气网航 2010-06-09
  • 打赏
  • 举报
回复
顶楼上的
yueguangkai001 2010-06-09
  • 打赏
  • 举报
回复
既然是ping就用ping来做萨

private String pingIP(String IP)
{
BufferedReader in = null;
Runtime rt = Runtime.getRuntime();
boolean FoundMatch = false;
String pingCommand = "ping " + IP + " -w " + 3000;
try
{
Process pro = rt.exec(pingCommand);
in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = in.readLine();
while (line != null)
{

try
{
Pattern Regex = Pattern.compile("(T|t){2}(L|l)",
Pattern.CANON_EQ);
Matcher RegexMatcher = Regex.matcher(line);
FoundMatch = RegexMatcher.find();
if (FoundMatch)
{
pro.destroy();
return IP.trim();
}
}
catch (PatternSyntaxException ex)
{
// Syntax error in the regular expression
ex.getMessage();
}
line = in.readLine();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
Debug.printExc(e.getMessage());
}
return null;
}
Mybeautiful 2010-06-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 yueguangkai001 的回复:]
既然是ping就用ping来做萨

Java code

private String pingIP(String IP)
{
BufferedReader in = null;
Runtime rt = Runtime.getRuntime();
boolean FoundMatch = false;
St……
[/Quote]

只能这样,楼主,我已经尝试很多次了....这是唯一的方案,目前为止我发现可行的。
eve_zz 2010-06-09
  • 打赏
  • 举报
回复
用java.net.InetAddress类中的
public boolean isReachable(int timeout) throws IOException
lxw886 2010-06-09
  • 打赏
  • 举报
回复
继续等待好的方法~
「已注销」 2010-06-08
  • 打赏
  • 举报
回复
mark~
欢乐极客 2010-06-08
  • 打赏
  • 举报
回复
重新写个类封装下呀
lxw886 2010-06-08
  • 打赏
  • 举报
回复
自己先顶~

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧