1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.pcap;
17
18 import io.netty.buffer.ByteBuf;
19
20 final class IPPacket {
21
22 private static final byte MAX_TTL = (byte) 255;
23 private static final short V4_HEADER_SIZE = 20;
24 private static final byte TCP = 6 & 0xff;
25 private static final byte UDP = 17 & 0xff;
26
27
28
29
30 private static final int IPV6_VERSION_TRAFFIC_FLOW = 60000000;
31
32 private IPPacket() {
33
34 }
35
36
37
38
39
40
41
42
43
44 static void writeUDPv4(ByteBuf byteBuf, ByteBuf payload, int srcAddress, int dstAddress) {
45 writePacketv4(byteBuf, payload, UDP, srcAddress, dstAddress);
46 }
47
48
49
50
51
52
53
54
55
56 static void writeUDPv6(ByteBuf byteBuf, ByteBuf payload, byte[] srcAddress, byte[] dstAddress) {
57 writePacketv6(byteBuf, payload, UDP, srcAddress, dstAddress);
58 }
59
60
61
62
63
64
65
66
67
68 static void writeTCPv4(ByteBuf byteBuf, ByteBuf payload, int srcAddress, int dstAddress) {
69 writePacketv4(byteBuf, payload, TCP, srcAddress, dstAddress);
70 }
71
72
73
74
75
76
77
78
79
80 static void writeTCPv6(ByteBuf byteBuf, ByteBuf payload, byte[] srcAddress, byte[] dstAddress) {
81 writePacketv6(byteBuf, payload, TCP, srcAddress, dstAddress);
82 }
83
84 private static void writePacketv4(ByteBuf byteBuf, ByteBuf payload, int protocol, int srcAddress,
85 int dstAddress) {
86
87 byteBuf.writeByte(0x45);
88 byteBuf.writeByte(0x00);
89 byteBuf.writeShort(V4_HEADER_SIZE + payload.readableBytes());
90 byteBuf.writeShort(0x0000);
91 byteBuf.writeShort(0x0000);
92 byteBuf.writeByte(MAX_TTL);
93 byteBuf.writeByte(protocol);
94 byteBuf.writeShort(0);
95 byteBuf.writeInt(srcAddress);
96 byteBuf.writeInt(dstAddress);
97 byteBuf.writeBytes(payload);
98 }
99
100 private static void writePacketv6(ByteBuf byteBuf, ByteBuf payload, int protocol, byte[] srcAddress,
101 byte[] dstAddress) {
102
103 byteBuf.writeInt(IPV6_VERSION_TRAFFIC_FLOW);
104 byteBuf.writeShort(payload.readableBytes());
105 byteBuf.writeByte(protocol & 0xff);
106 byteBuf.writeByte(MAX_TTL);
107 byteBuf.writeBytes(srcAddress);
108 byteBuf.writeBytes(dstAddress);
109 byteBuf.writeBytes(payload);
110 }
111 }