Golang:如何检查HTTP请求是否在TCP有效负载字节中

I am using the gopacket package and every time I have a TCP packet I want to check if the payload contains an HTTP request. Is there an easy way to do that instead of writing my own parser? There is also a function (see: func ReadRequest(b *bufio.Reader)) which returns a Request struct but I do not know what kind of input I should use. tcp.Payload is the byte[] array that seems to have the information I need to parse (see the following example):

// Get the TCP layer from this packet
if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
    fmt.Printf("TCP ")
    // Get actual TCP data from this layer
    tcp, _ := tcpLayer.(*layers.TCP)
    srcPort = tcp.SrcPort
    dstPort = tcp.DstPort
    if tcp.SYN {
        fmt.Print("[SYN] ")
    }
    if tcp.ACK {
        fmt.Print("[ACK] ")
    }
    if tcp.FIN {
        fmt.Print("[FIN] ")
    }
    fmt.Printf("%s:%d > %s:%d ", srcIP, srcPort, dstIP, dstPort)

    fmt.Println(string(tcp.Payload))
}

After sending an HTTP request I get the following output:

PKT [001] TCP [SYN] 192.168.2.6:59095 > 192.168.3.5:80
PKT [002] TCP [SYN] [ACK] 192.168.3.5:80 > 192.168.2.6:59095
PKT [003] TCP [ACK] 192.168.2.6:59095 > 192.168.3.5:80
PKT [004] TCP [ACK] 192.168.2.6:59095 > 192.168.3.5:80 GET /certificates/test.pdf HTTP/1.1
User-Agent: Wget/1.15 (linux-gnu)
Accept: */*
Host: 192.168.3.5
Connection: Keep-Alive

Any suggestions are welcome...

doupingmao1903
doupingmao1903 是的,如果有效负载包含完整的请求,则可以将其提供给http.ReadRequst。这种较简单的情况并不是真正有用,因为您正在处理TCP流的各个数据包。当您考虑到请求可以在数据包有效负载中间开始的可能性时,该请求立即失败,并且该请求仍很可能跨越多个数据包。HTTP的级别高于TCP,并且您需要重新组装流(流),然后才能正确解析HTTP。
大约 4 年之前 回复
duan0417
duan0417 是的,让我们来看一个简单的情况,即有效负载只有一个HTTP请求并且没有丢失的部分
大约 4 年之前 回复
dongteng2534
dongteng2534 您是否要检查数据包是否具有HTTP请求的开始?单个请求可能会跨越多个数据包。
大约 4 年之前 回复

1个回答



在此问题的帮助下:如何在Go中解析http标头,以下尝试使用 http.ReadRequest()</ code>起作用... </ p>

< pre> if tcpLayer:= packet.Layer(layers.LayerTypeTCP); tcpLayer!= nil {
tcp,_:= tcpLayer。(* layers.TCP)
如果len(tcp.Payload)!= 0 {
reader:= bufio.NewReader(bytes.NewReader(tcp.Payload) )
httpReq,err:= http.ReadRequest(阅读器)
...
}
}
</ code> </ pre>
</ div>

展开原文

原文

With help from this question: How to parse http headers in Go the following attempt with http.ReadRequest() works...

if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
   tcp, _ := tcpLayer.(*layers.TCP)
   if len(tcp.Payload) != 0 {
      reader := bufio.NewReader(bytes.NewReader(tcp.Payload))
      httpReq, err := http.ReadRequest(reader)
      ...
  }
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐