我正在编写一个程序,它读取通过运行它的计算机的所有数据包。我希望抓取一个数据包(通过 dst ip 或 src ip),然后更改 dstIP 和 TCP dstPort 并将其放回线路上。
我对更改 dstIP 没有任何问题,但是如何正确序列化它以使数据包不会出现格式错误并到达我希望它去的目的地?
package main
import (
"code.google.com/p/gopacket"
"code.google.com/p/gopacket/layers"
"code.google.com/p/gopacket/pcap"
"fmt"
"net"
)
func main() {
if handle, err := pcap.OpenLive("wlp4s0", 1600, true, 100); err != nil {
panic(err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
fmt.Println("This is a IP packet!")
// Get actual IP data from this layer
ip, _ := ipLayer.(*layers.IPv4)
//see if the source IP is what I'm expecting
if ip.SrcIP.Equal(net.ParseIP("192.168.1.66")) {
//change the dst IP to something 192.168.1.65
ip.DstIP = net.ParseIP("192.168.1.65")
// create a buffer to serialize to
buf := gopacket.NewSerializeBuffer()
//no options
opts := gopacket.SerializeOptions{}
//serialize the packet
ip.SerializeTo(buf, opts)
packetDataToGo := buf.Bytes()
// send the packet
handle.WritePacketData(packetDataToGo)
}
}
}
}
}