I'm writing a program that reads all packets passing through the computer running it. I wish to grab a packet (either by dst ip or src ip), then change the dstIP and TCP dstPort and put it back on the wire.
I have no problems with changing the dstIP, but how do I serialize it properly so the packet isn't malformed and gets to the destination in which I want it to go?
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)
}
}
}
}
}