java 如何使用Java将自定义数据写入TCP数据包头选项字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2653262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:13:24  来源:igfitidea点击:

How to write custom data to the TCP packet header options field with Java?

javatcpoptions

提问by Matlabber

As it is defined (see: http://www.freesoft.org/CIE/Course/Section4/8.htm) the TCP header has an 'Options' field. There are a couple of options already defined (see: www.iana.org/assignments/tcp-parameters/) but I want to come up with my very own. (For experimenting/research.)

正如它所定义的(参见:http: //www.freesoft.org/CIE/Course/Section4/8.htm),TCP 标头有一个“选项”字段。已经定义了几个选项(参见:www.iana.org/assignments/tcp-parameters/)但我想提出我自己的。(用于实验/研究。)

How can I get Java to write (and then read) some custom data to the options field?

如何让 Java 向选项字段写入(然后读取)一些自定义数据?

Bonus question: if it cannot be done with Java. what kind of application can do this? (No, I don't really feel like messing with some kernel-level TCP/IP stack implementation, I want to keep it app level.)

额外的问题:如果它不能用 Java 完成。什么样的应用程序可以做到这一点?(不,我真的不想弄乱一些内核级 TCP/IP 堆栈实现,我想保持它的应用程序级别。)

Thanks!

谢谢!

回答by h3xStream

JNetPcap is a library that will allow you to change headers from low level layers including TCP. http://jnetpcap.com/node/29

JNetPcap 是一个库,允许您从低层(包括 TCP)更改标头。 http://jnetpcap.com/node/29

Here is a quick example:

这是一个快速示例:

byte[] pktBytes = FormatUtils.toByteArray("0015c672234c90e6ba92661608004500002d358c4000800600000a000b050a090028c26e270fb8b256e3a2009f785018faf01f550000746573740a");
JMemoryPacket packet = new JMemoryPacket(pktBytes);

packet.scan(Ethernet.ID); //Need to be done before doing any edits

//Editing Ip layer
Ip4 ip = packet.getHeader(new Ip4());
ip.source(new byte[] {2,6,0,0}); //Source Ip 2.6.0.0
ip.destination(new byte[] {1,2,3,4}); //Dest Ip 1.2.3.4

//Editing Tcp layer
Tcp tcp = packet.getHeader(new Tcp());
tcp.destination(5555); //Port destination 5555

if (pcap.sendPacket(packet) != Pcap.OK) {
    System.err.println(pcap.getErr());
}