Preface
Java is a cross-platform language. Generally, network operations are performed at or above the IP layer, that is, only tcp/udp operations can be performed. Of course, you can also set some options for tcp/udp, if you want to perform operations on the IP layer or data link layer, you can do nothing. You must rely on jni to use the socket interfaces of the local OS. Fortunately, I know that someone is developing jpcap when I know winpcap. This package allows you to conveniently operate the underlying network application protocol. The following is a detailed description.
Procedure
Download the required package quota.
You can use any ide tool you like, but you must add jpcap. jar to classpath; otherwise, it cannot be compiled. Icmp has many types. Currently, only the echo type is used as an example, that is, the network behavior generated by using the ping tool. The following code is detailed.
- Import java.net. InetAddress;
- Import jpcap. JpcapCaptor;
- Import jpcap. JpcapSender;
- Import jpcap. NetworkInterface;
- Import jpcap. packet. EthernetPacket;
- Import jpcap. packet. ICMPPacket;
- Import jpcap. packet. IPPacket;
- Class ICMP
- {
- Public static void main (String [] args) throws java. io. IOException {
- NetworkInterface [] devices = JpcapCaptor. getDeviceList ();
- If (args. length <1 ){
- System. out. println ("Usage: java ICMP ");
- For (int I = 0; I
- System. out. println (I + ":" + devices [I]. name + "(" + devices [I]. description + ")");
- System. exit (0 );
- }
- Int index = Integer. parseInt (args [0]);
- // Enable the network device
- JpcapCaptor captor = JpcapCaptor. openDevice (devices [index], 2000, false, 3000 );
- // Set to filter only icmp Packets
- Captor. setFilter ("icmp", true );
- JpcapSender sender = captor. getJpcapSenderInstance ();
- ICMPPacket p = new ICMPPacket ();
- P. type = ICMPPacket. ICMP_ECHO;
- P. seq = (short) 0x0005;
- P. id = (short) 0x0006;
- P. setIPv4Parameter (0, false, 0, false, 0,10101, 100, IPPacket. IPPROTO_ICMP,
- InetAddress. getByName ("192.168.1.30"), InetAddress. getByName ("192.168.1.1 "));
- P. data = "abcdefghijklmnopqrstuvwabcdehghi". getBytes ();
- EthernetPacket ether = new EthernetPacket ();
- Ether. frametype = EthernetPacket. ETHERTYPE_IP;
- // Enter the mac address of the user and the other user, which must be filled in correctly. If an error occurs, the user cannot receive the response packet.
- Ether. dst_mac = new byte [] {(byte) 0x00, (byte) 0x03, (byte) 0x2d, (byte) 0x02, (byte) 0xd1, (byte) 0x69 };
- Ether. src_mac = new byte [] {(byte) 0x08, (byte) 0x00, (byte) 0x46, (byte) 0xad, (byte) 0x3c, (byte) 0x12 };
- P. datalink = ether;
- Sender. sendPacket (p );
- System. out. println ("send ...");
- ICMPPacket rp = null;
- While (true ){
- Rp = (ICMPPacket) captor. getPacket ();
- If (rp = null ){
- Throw new IllegalArgumentException ("no rcv icmp echo reply ");
- } Else
- {
- System. out. println ("rcv icmp echo reply ");
- Return;
- }
- }
- }
- }