Ping一个IP以接收ping

时间:2015-04-01 05:21:30

标签: java networking ip ping

我需要创建一个程序,将一个ping或一些信息(如字符串“check”)发送到网络上的所有IP地址,并在某个客户端处于活动状态时从该IP获取信息。我想收到一些告诉我的客户其他客户正常工作和运行的东西。我也不确定如何在不将ping发送到不存在的位置的情况下向所有网络位置发送信息。另外,我怎样才能知道IP主要客户端发送的信息是什么?例如,我想从我的主客户端向网络上的所有位置发送“检查”,如果网络上有计算机与我的其他客户端,它将收到“检查”并发送“确定”与他们的IP。这是一个学校项目,我的老师真的很困惑我。到目前为止,我没有尝试过任何工作。

1 个答案:

答案 0 :(得分:1)

你可以在java中使用Socket编程,也可以使用jpcap库来发送数据包。 用于发送数据包的Jpcap示例代码。

import java.net.InetAddress;

import jpcap.*;
import jpcap.packet.EthernetPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.TCPPacket;

class SendTCP
{
public static void main(String[] args) throws java.io.IOException{
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
if(args.length<1){
System.out.println(“Usage: java SentTCP <device index (e.g., 0, 1..)>”);
for(int i=0;i<devices.length;i++)
System.out.println(i+”:”+devices[i].name+”(“+devices[i].description+”)”);
System.exit(0);
}
int index=Integer.parseInt(args[0]);
JpcapSender sender=JpcapSender.openDevice(devices[index]);

TCPPacket p=new TCPPacket(12,34,56,78,false,false,false,false,true,true,true,true,10,10);
p.setIPv4Parameter(0,false,false,false,0,false, false,false,0,1010101,100,IPPacket.IPPROTO_TCP,
InetAddress.getByName(“www.microsoft.com”),
InetAddress.getByName(“www.google.com”));
p.data=(“data”).getBytes();

EthernetPacket ether=new EthernetPacket();
ether.frametype=EthernetPacket.ETHERTYPE_IP;
ether.src_mac=new byte[]{(byte)0,(byte)1,(byte)2,(byte)3,(byte)4,(byte)5};
ether.dst_mac=new byte[]{(byte)0,(byte)6,(byte)7,(byte)8,(byte)9,(byte)10};
p.datalink=ether;

for(int i=0;i<10;i++)
sender.sendPacket(p);
}
}

接收数据包的示例程序。

import jpcap.*;
import jpcap.packet.Packet;

class Tcpdump implements PacketReceiver {
public void receivePacket(Packet packet) {
System.out.println(packet);
}

public static void main(String[] args) throws Exception {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
if(args.length<1){
System.out.println(“usage: java Tcpdump <select a number from the following>”);

for (int i = 0; i < devices.length; i++) {
System.out.println(i+” :”+devices[i].name + “(” + devices[i].description+”)”);
System.out.println(” data link:”+devices[i].datalink_name + “(”
+ devices[i].datalink_description+”)”);
System.out.print(” MAC address:”);
for (byte b : devices[i].mac_address)
System.out.print(Integer.toHexString(b&0xff) + “:”);
System.out.println();
for (NetworkInterfaceAddress a : devices[i].addresses)
System.out.println(” address:”+a.address + ” ” + a.subnet + ” ”
+ a.broadcast);
}
}else{
JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])], 2000, false, 20);

jpcap.loopPacket(-1, new Tcpdump());
}
}
}

参考此link