【用java实现tcp/ip】1、win10下使用jpcap获取网卡硬件
程序员文章站
2022-07-01 14:51:26
...
IDEA导入jpcap的jar包,关于资料的下载见文章末尾。
package networkCard;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.PacketReceiver;
import jpcap.packet.Packet;
import java.io.IOException;
public class ProtocolEntry implements PacketReceiver {
public void receivePacket(Packet packet) {
System.out.println(packet);
System.out.println("Receive a packet");
}
public static void main(String[] args) throws IOException {
// System.out.println(System.getProperty("java.library.path"));
//获取网卡列表
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
JpcapCaptor captor = null;
for (int i = 0; i < devices.length; i++) {
//显示网卡名字
System.out.println(i+": "+devices[i].name + "(" + devices[i].description + ")");
System.out.println(" datalink: " + devices[i].datalink_name + "(" + devices[i].datalink_description + ")");
System.out.println(" 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);
}
captor = JpcapCaptor.openDevice(devices[i], 65536, false, 20);
if (captor != null) {
System.out.println("Open captor on device" + i);
break;
}
}
}
}
如果包no jpcap in java.library.path这个错误,那就需要我们把Jpcap.dll放在java.library.path路径下,这个路径可以通过System.out.println(System.getProperty(“java.library.path”));打印出来,有多个,随便放在其中一个路径就可以了。
再次运行,打印信息如下:
0: \Device\NPF_{1AE86BDA-2AB9-44D5-A6BC-967CB285F9FC}(Oracle)
datalink: EN10MB(Ethernet)
Mac Address:
a:0:27:0:0:4:
address:/fe80:0:0:0:7517:9ae7:4ef:d5cc null null
address:/192.168.56.1 /255.255.255.0 /255.255.255.255
Open captor on device0
上面代码中有这样一行,用来打开网络接口,
JpcapCaptor.openDevice(devices[i], 65536, false, 20);
其中参数的含义如下,
名称 | 目的 |
---|---|
NetworkInterderface intrface | 要打开的网络接口 |
int snaplen | 一次捕获数据包的最大byte数 |
boolean prommics | 是否采用混乱模式,采用的话可以捕获所有数据包,即便源MAC或目的MAC地址与打开的网络接口的MAC地址不相同 |
int to_ms | 捕获的数据包的超时设置(数量级为毫秒)。 |
资料下载:
download.csdn.net/download/m0_46130323/12530123
download.csdn.net/download/m0_46130323/12530113
参考文章:
https://www.jianshu.com/p/b72f951c971f
上一篇: IP协议