本文整理汇总了Golang中github.com/google/gopacket/layers.TCP类的典型用法代码示例。如果您正苦于以下问题:Golang TCP类的具体用法?Golang TCP怎么用?Golang TCP使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TCP类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: decodePackets
func (i *Sniffer) decodePackets() {
var eth layers.Ethernet
var ip layers.IPv4
var tcp layers.TCP
var payload gopacket.Payload
parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip, &tcp, &payload)
decoded := make([]gopacket.LayerType, 0, 4)
for {
select {
case <-i.stopDecodeChan:
return
case timedRawPacket := <-i.decodePacketChan:
newPayload := new(gopacket.Payload)
payload = *newPayload
err := parser.DecodeLayers(timedRawPacket.RawPacket, &decoded)
if err != nil {
continue
}
flow := types.NewTcpIpFlowFromFlows(ip.NetworkFlow(), tcp.TransportFlow())
packetManifest := types.PacketManifest{
Timestamp: timedRawPacket.Timestamp,
Flow: flow,
RawPacket: timedRawPacket.RawPacket,
IP: ip,
TCP: tcp,
Payload: payload,
}
i.dispatcher.ReceivePacket(&packetManifest)
}
}
}
示例2: makeTestPacket
func makeTestPacket() []byte {
var testSeq uint32 = 12345
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
eth := layers.Ethernet{
SrcMAC: net.HardwareAddr{0xde, 0xad, 0xbe, 0xee, 0xee, 0xff},
DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
}
ip := layers.IPv4{
SrcIP: net.IP{1, 2, 3, 4},
DstIP: net.IP{2, 3, 4, 5},
Version: 4,
TTL: 64,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SYN: true,
SrcPort: 1,
DstPort: 2,
Seq: testSeq,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},
}
tcp.SetNetworkLayerForChecksum(&ip)
gopacket.SerializeLayers(buf, opts, ð, &ip, &tcp)
packetData := buf.Bytes()
return packetData
}
示例3: NewTcpIpFlowFromPacket
// getPacketFlow returns a TcpIpFlow struct given a byte array packet
func NewTcpIpFlowFromPacket(packet []byte) (*TcpIpFlow, error) {
var ip layers.IPv4
var tcp layers.TCP
decoded := []gopacket.LayerType{}
parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &ip, &tcp)
err := parser.DecodeLayers(packet, &decoded)
if err != nil {
return &TcpIpFlow{}, err
}
return &TcpIpFlow{
ipFlow: ip.NetworkFlow(),
tcpFlow: tcp.TransportFlow(),
}, nil
}
示例4: BenchmarkMultiStreamGrow
func BenchmarkMultiStreamGrow(b *testing.B) {
t := layers.TCP{
SrcPort: 1,
DstPort: 2,
Seq: 0,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}},
}
a := NewAssembler(NewStreamPool(&testFactory{}))
for i := 0; i < b.N; i++ {
t.SrcPort = layers.TCPPort(i)
a.Assemble(netFlow, &t)
t.Seq += 10
}
}
示例5: BenchmarkSingleStreamLoss
func BenchmarkSingleStreamLoss(b *testing.B) {
t := layers.TCP{
SrcPort: 1,
DstPort: 2,
SYN: true,
Seq: 1000,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}},
}
a := NewAssembler(NewStreamPool(&testFactory{}))
for i := 0; i < b.N; i++ {
a.Assemble(netFlow, &t)
t.SYN = false
t.Seq += 11
}
}
示例6: TestGetOverlapRingsWithZeroRings
func TestGetOverlapRingsWithZeroRings(t *testing.T) {
ip := layers.IPv4{
SrcIP: net.IP{1, 2, 3, 4},
DstIP: net.IP{2, 3, 4, 5},
Version: 4,
TTL: 64,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SYN: true,
SrcPort: 1,
DstPort: 2,
}
tcp.SetNetworkLayerForChecksum(&ip)
payload := gopacket.Payload([]byte{1, 2, 3, 4})
p := types.PacketManifest{
IP: ip,
TCP: tcp,
Payload: payload,
}
options := ConnectionOptions{
MaxBufferedPagesTotal: 0,
MaxBufferedPagesPerConnection: 0,
MaxRingPackets: 40,
PageCache: nil,
LogDir: "fake-log-dir",
}
f := &DefaultConnFactory{}
conn := f.Build(options).(*Connection)
ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))
tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))
serverFlow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)
clientFlow := serverFlow.Reverse()
conn.serverFlow = serverFlow
conn.clientFlow = clientFlow
head, tail := getOverlapRings(&p, serverFlow, conn.ClientStreamRing)
if head == nil || tail == nil {
return
} else {
t.Fail()
}
return
}
示例7: sendPacket
func sendPacket(handle *pcap.Handle, sMac, dMac net.HardwareAddr, sIp, dIp net.IP, sPort, dPort layers.TCPPort, IpId uint16, IpTtl uint8, TcpSeq, ack uint32, WindowsSize uint16, data []byte) error {
eth := layers.Ethernet{
SrcMAC: sMac,
DstMAC: dMac,
EthernetType: layers.EthernetTypeIPv4,
}
ip4 := layers.IPv4{
SrcIP: sIp,
DstIP: dIp,
Id: IpId,
Flags: layers.IPv4DontFragment,
Version: 4,
TTL: IpTtl,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SrcPort: sPort,
DstPort: dPort,
Seq: TcpSeq,
ACK: true,
Ack: ack,
Window: WindowsSize,
PSH: true, // 立刻处理
}
if len(data) == 0 {
tcp.RST = true
}
tcp.SetNetworkLayerForChecksum(&ip4)
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
payload := gopacket.Payload(data)
if err := gopacket.SerializeLayers(buf, opts, ð, &ip4, &tcp, payload); err != nil {
return err
}
return handle.WritePacketData(buf.Bytes())
}
示例8: BenchmarkMultiStreamConn
func BenchmarkMultiStreamConn(b *testing.B) {
t := layers.TCP{
SrcPort: 1,
DstPort: 2,
Seq: 0,
SYN: true,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}},
}
a := NewAssembler(NewStreamPool(&testFactory{}))
for i := 0; i < b.N; i++ {
t.SrcPort = layers.TCPPort(i)
a.Assemble(netFlow, &t)
if i%65536 == 65535 {
if t.SYN {
t.SYN = false
t.Seq += 1
}
t.Seq += 10
}
}
}
示例9: TestNewTcpIpFlowFromPacket
func TestNewTcpIpFlowFromPacket(t *testing.T) {
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
ip := layers.IPv4{
SrcIP: net.IP{1, 2, 3, 4},
DstIP: net.IP{2, 3, 4, 5},
Version: 4,
TTL: 64,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SYN: true,
SrcPort: 1,
DstPort: 2,
Seq: 123,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},
}
tcp.SetNetworkLayerForChecksum(&ip)
gopacket.SerializeLayers(buf, opts, &ip, &tcp)
packetData := buf.Bytes()
flow1, err := NewTcpIpFlowFromPacket(packetData)
ipFlow2, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))
tcpFlow2, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))
flow2 := NewTcpIpFlowFromFlows(ipFlow2, tcpFlow2)
if err != nil && !flow2.Equal(flow1) {
t.Error("NewTcpIpFlowFromPacket fail")
t.Fail()
}
flow1, err = NewTcpIpFlowFromPacket([]byte{1, 2, 3, 4, 5, 6, 7})
if err == nil || !flow1.Equal(&TcpIpFlow{}) {
t.Error("NewTcpIpFlowFromPacket fail")
t.Fail()
}
}
示例10: BenchmarkSingleStreamSkips
func BenchmarkSingleStreamSkips(b *testing.B) {
t := layers.TCP{
SrcPort: 1,
DstPort: 2,
SYN: true,
Seq: 1000,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}},
}
a := NewAssembler(NewStreamPool(&testFactory{}))
skipped := false
for i := 0; i < b.N; i++ {
if i%10 == 9 {
t.Seq += 10
skipped = true
} else if skipped {
t.Seq -= 20
}
a.Assemble(netFlow, &t)
if t.SYN {
t.SYN = false
t.Seq++
}
t.Seq += 10
if skipped {
t.Seq += 10
skipped = false
}
}
}
示例11: TestSequenceFromPacket
func TestSequenceFromPacket(t *testing.T) {
var testSeq uint32 = 12345
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
ip := layers.IPv4{
SrcIP: net.IP{1, 2, 3, 4},
DstIP: net.IP{2, 3, 4, 5},
Version: 4,
TTL: 64,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SYN: true,
SrcPort: 1,
DstPort: 2,
Seq: testSeq,
BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},
}
tcp.SetNetworkLayerForChecksum(&ip)
gopacket.SerializeLayers(buf, opts, &ip, &tcp)
packetData := buf.Bytes()
seq, err := SequenceFromPacket(packetData)
if err != nil && seq != testSeq {
t.Error("SequenceFromPacket failed")
t.Fail()
}
seq, err = SequenceFromPacket([]byte{1, 2, 3})
if err == nil {
t.Error("SequenceFromPacket should have failed")
t.Fail()
}
}
示例12: injectPacketFromDst
func (r *RawSocketServer) injectPacketFromDst(tcpLayer *layers.TCP, rawBytes []byte) error {
// Preparing ipLayer.
ipLayer := &layers.IPv4{
SrcIP: r.dst.ip,
DstIP: r.src.ip,
Version: 4,
TTL: 64,
Protocol: layers.IPProtocolTCP,
}
options := gopacket.SerializeOptions{
ComputeChecksums: true,
FixLengths: true,
}
tcpLayer.SrcPort = r.dst.port
tcpLayer.DstPort = r.src.port
tcpLayer.Window = r.window
tcpLayer.Ack = r.ack
tcpLayer.Seq = r.seq
tcpLayer.SetNetworkLayerForChecksum(ipLayer)
// And create the packet with the layers
buffer := gopacket.NewSerializeBuffer()
gopacket.SerializeLayers(buffer, options,
ipLayer,
tcpLayer,
gopacket.Payload(rawBytes),
)
outgoingPacket := buffer.Bytes()
p := tuntap.Packet{
Protocol: 0x800,
Truncated: false,
Packet: outgoingPacket,
}
return r.iface.WritePacket(&p)
}
示例13: main
func main() {
defer util.Run()()
var handle *pcap.Handle
var err error
if *fname != "" {
if handle, err = pcap.OpenOffline(*fname); err != nil {
log.Fatal("PCAP OpenOffline error:", err)
}
} else {
// This is a little complicated because we want to allow all possible options
// for creating the packet capture handle... instead of all this you can
// just call pcap.OpenLive if you want a simple handle.
inactive, err := pcap.NewInactiveHandle(*iface)
if err != nil {
log.Fatal("could not create: %v", err)
}
defer inactive.CleanUp()
if err = inactive.SetSnapLen(*snaplen); err != nil {
log.Fatal("could not set snap length: %v", err)
} else if err = inactive.SetPromisc(*promisc); err != nil {
log.Fatal("could not set promisc mode: %v", err)
} else if err = inactive.SetTimeout(time.Second); err != nil {
log.Fatal("could not set timeout: %v", err)
}
if *tstype != "" {
if t, err := pcap.TimestampSourceFromString(*tstype); err != nil {
log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps())
} else if err := inactive.SetTimestampSource(t); err != nil {
log.Fatalf("Supported timestamp types: %v", inactive.SupportedTimestamps())
}
}
inactive.SetImmediateMode(true)
if handle, err = inactive.Activate(); err != nil {
log.Fatal("PCAP Activate error:", err)
}
defer handle.Close()
if len(flag.Args()) > 0 {
bpffilter := strings.Join(flag.Args(), " ")
fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
if err = handle.SetBPFFilter(bpffilter); err != nil {
log.Fatal("BPF filter error:", err)
}
}
}
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
if tcpLayer.(*layers.TCP).DstPort != 80 {
continue
}
if tcpLayer.(*layers.TCP).SYN || tcpLayer.(*layers.TCP).RST {
continue
}
data := string(tcpLayer.(*layers.TCP).LayerPayload())
if !strings.HasPrefix(data, "GET") {
continue
}
fmt.Println("I got GET packet!")
ethLayer := packet.Layer(layers.LayerTypeEthernet)
eth := layers.Ethernet{
SrcMAC: ethLayer.(*layers.Ethernet).DstMAC,
DstMAC: ethLayer.(*layers.Ethernet).SrcMAC,
EthernetType: layers.EthernetTypeIPv4,
}
ipv4Layer := packet.Layer(layers.LayerTypeIPv4)
ipv4 := layers.IPv4{
Version: ipv4Layer.(*layers.IPv4).Version,
SrcIP: ipv4Layer.(*layers.IPv4).DstIP,
DstIP: ipv4Layer.(*layers.IPv4).SrcIP,
TTL: 77,
Id: ipv4Layer.(*layers.IPv4).Id,
Protocol: layers.IPProtocolTCP,
}
tcp := layers.TCP{
SrcPort: tcpLayer.(*layers.TCP).DstPort,
DstPort: tcpLayer.(*layers.TCP).SrcPort,
PSH: true,
ACK: true,
FIN: true,
Seq: tcpLayer.(*layers.TCP).Ack,
Ack: tcpLayer.(*layers.TCP).Seq + uint32(len(data)),
Window: 0,
}
tcp.SetNetworkLayerForChecksum(&ipv4)
data =
`HTTP/1.1 200 OK
Server: nginx
Date: Tue, 26 Jan 2016 13:09:19 GMT
Content-Type: text/plain;charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-store
Pragrma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache
Content-Length: 7
Stupid!`
//.........这里部分代码省略.........
示例14: AssembleWithTimestamp
// AssembleWithTimestamp reassembles the given TCP packet into its appropriate
// stream.
//
// The timestamp passed in must be the timestamp the packet was seen. For
// packets read off the wire, time.Now() should be fine. For packets read from
// PCAP files, CaptureInfo.Timestamp should be passed in. This timestamp will
// affect which streams are flushed by a call to FlushOlderThan.
//
// Each Assemble call results in, in order:
//
// zero or one calls to StreamFactory.New, creating a stream
// zero or one calls to Reassembled on a single stream
// zero or one calls to ReassemblyComplete on the same stream
func (a *Assembler) AssembleWithTimestamp(netFlow gopacket.Flow, t *layers.TCP, timestamp time.Time) {
// Ignore empty TCP packets
if !t.SYN && !t.FIN && !t.RST && len(t.LayerPayload()) == 0 {
return
}
a.ret = a.ret[:0]
key := key{netFlow, t.TransportFlow()}
var conn *connection
// This for loop handles a race condition where a connection will close,
// lock the connection pool, and remove itself, but before it locked the
// connection pool it's returned to another Assemble statement. This should
// loop 0-1 times for the VAST majority of cases.
for {
conn = a.connPool.getConnection(
key, !t.SYN && len(t.LayerPayload()) == 0, timestamp)
if conn == nil {
if *debugLog {
log.Printf("%v got empty packet on otherwise empty connection", key)
}
return
}
conn.mu.Lock()
if !conn.closed {
break
}
conn.mu.Unlock()
}
if conn.lastSeen.Before(timestamp) {
conn.lastSeen = timestamp
}
seq, bytes := Sequence(t.Seq), t.Payload
if conn.nextSeq == invalidSequence {
// Handling the first packet we've seen on the stream.
skip := 0
if !t.SYN {
// don't add 1 since we're just going to assume the sequence number
// without the SYN packet.
// stream was picked up somewhere in the middle, so indicate that we
// don't know how many packets came before it.
conn.nextSeq = seq.Add(len(bytes))
skip = -1
} else {
// for SYN packets, also increment the sequence number by 1
conn.nextSeq = seq.Add(len(bytes) + 1)
}
a.ret = append(a.ret, tcpassembly.Reassembly{
Bytes: bytes,
Skip: skip,
Start: t.SYN,
Seen: timestamp,
})
a.insertIntoConn(t, conn, timestamp)
} else if diff := conn.nextSeq.Difference(seq); diff > 0 {
a.insertIntoConn(t, conn, timestamp)
} else {
bytes, conn.nextSeq = byteSpan(conn.nextSeq, seq, bytes)
a.ret = append(a.ret, tcpassembly.Reassembly{
Bytes: bytes,
Skip: 0,
End: t.RST || t.FIN,
Seen: timestamp,
})
}
if len(a.ret) > 0 {
a.sendToConnection(conn)
}
conn.mu.Unlock()
}
示例15: handleTCP
func (vnet *VNET) handleTCP(pkt *Packet, now time.Time) {
// fmt.Printf("TCP: %08x %s\n", pkt.Flags, pkt.String())
defer pkt.Release()
var err error
if bytes.Equal(pkt.Eth.DstMAC, layers.EthernetBroadcast[:]) {
// ignore
return
}
if pkt.DstHost == nil {
// ignore
return
}
if !pkt.DstHost.Up {
log.Printf("destination is down: %s", pkt.DstHost.Name)
// ignore
return
}
var (
srcIP net.IP
dstIP net.IP
srcPort = uint16(pkt.TCP.SrcPort)
dstPort = uint16(pkt.TCP.DstPort)
)
if pkt.IPv4 != nil {
srcIP = CloneIP(pkt.IPv4.SrcIP.To16())
dstIP = CloneIP(pkt.IPv4.DstIP.To16())
} else if pkt.IPv6 != nil {
srcIP = CloneIP(pkt.IPv6.SrcIP.To16())
dstIP = CloneIP(pkt.IPv6.DstIP.To16())
} else {
log.Printf("invalid protocol")
// ignore
return
}
route := vnet.routes.GetTable().Lookup(
protocols.TCP,
srcIP, dstIP, srcPort, dstPort)
if route == nil {
rule, found := vnet.rules.GetTable().Lookup(protocols.TCP, pkt.DstHost.ID, dstPort)
if !found {
log.Printf("no rule")
// ignore
return
}
var (
ruleDstIP = rule.DstIP
ruleDstPort = rule.DstPort
hostIP net.IP
hostPort uint16
)
if ruleDstIP != nil {
hostIP = dstIP
hostPort, err = vnet.ports.Allocate(pkt.DstHost.ID, protocols.TCP, 0)
if err != nil {
// ignore
log.Printf("TCP/error: %s", err)
return
}
var r routes.Route
r.Protocol = protocols.TCP
r.HostID = pkt.DstHost.ID
r.SetInboundSource(hostIP, hostPort)
r.SetInboundDestination(vnet.system.GatewayIPv4(), vnet.proxy.TCPPort)
r.SetOutboundDestination(ruleDstIP, rule.DstPort)
route, err = vnet.routes.AddRoute(&r)
if err != nil {
// ignore
log.Printf("TCP/error: %s", err)
return
}
ruleDstIP = vnet.system.GatewayIPv4()
ruleDstPort = vnet.proxy.TCPPort
}
if ruleDstIP == nil {
gateway := vnet.hosts.GetTable().LookupByName("gateway")
if gateway == nil || !gateway.Up {
log.Printf("no gateway")
// ignore
return
}
if dstIP.To4() != nil {
if len(gateway.IPv4Addrs) > 0 {
ruleDstIP = gateway.IPv4Addrs[0]
}
} else {
if len(gateway.IPv6Addrs) > 0 {
//.........这里部分代码省略.........