How to send tcp or udp packet?
formatwea opened this issue · comments
John Wick commented
I read and run SendArpReques.java in sample,according to this example,i try to build tcp packet,using TcpPacket.Builder(),IpV4Packet.Builder(),EthernetPacket.Builder(),add attribute in three layers. When i send packet to other pc which is running wireshark,i can not capture packet which i using pcap4j build.So,how to send tcp or udp packet?i want to ask that pcap4j is support to send tcp or udp packet or not?If it support,i want to know that how to build udp or tcp packet.thanks!!!!
John Wick commented
// build tcp
TcpPacket.Builder tcpBuilder = new TcpPacket.Builder();
try {
tcpBuilder
.srcPort(TcpPort.getInstance((short) 55321))
.dstPort(TcpPort.getInstance((short) 80))
.srcAddr(InetAddress.getByName("186.100.10.1"))
.dstAddr(InetAddress.getByName("186.100.9.1"))
.ack(true);
} catch (UnknownHostException e) {
e.printStackTrace();
}
// build ip
IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder();
try {
ipv4Builder
.version(IpVersion.IPV4)
.tos(IpV4Rfc791Tos.newInstance((byte) 0))
.dontFragmentFlag(true)
.moreFragmentFlag(false)
.fragmentOffset((short) 0)
.totalLength((short) 60)
.ttl((byte) 128)
.protocol(IpNumber.TCP)
.srcAddr((Inet4Address) InetAddress.getByName("186.100.10.1"))
.dstAddr((Inet4Address) InetAddress.getByName("186.100.9.1"))
.payloadBuilder(tcpBuilder);
} catch (UnknownHostException e) {
e.printStackTrace();
}
EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
etherBuilder
.dstAddr(MacAddress.getByName("ac:74:09:83:b2:dd"))
.srcAddr(MacAddress.getByName("A0:8C:FD:E6:99:53"))
.type(EtherType.IPV4)
.payloadBuilder(ipv4Builder)
.paddingAtBuild(true);
try {
PcapHandle sendHandle = pcapNetworkInterface.openLive(65535, PromiscuousMode.PROMISCUOUS, 10);
for (int i = 0; i < 5; i++) {
Packet p = etherBuilder.build();
System.out.println(p);
sendHandle.sendPacket(p);
}
} catch (PcapNativeException e) {
e.printStackTrace();
} catch (NotOpenException e) {
e.printStackTrace();
}
}