github.com/borderzero/water@v0.0.1/waterutil/tun_ipv4.go (about) 1 package waterutil 2 3 import ( 4 "net" 5 ) 6 7 func IPv4DSCP(packet []byte) byte { 8 return packet[1] >> 2 9 } 10 11 func IPv4ECN(packet []byte) byte { 12 return packet[1] & 0x03 13 } 14 15 func IPv4Identification(packet []byte) [2]byte { 16 return [2]byte{packet[4], packet[5]} 17 } 18 19 func IPv4TTL(packet []byte) byte { 20 return packet[8] 21 } 22 23 func IPv4Protocol(packet []byte) IPProtocol { 24 return IPProtocol(packet[9]) 25 } 26 27 func IPv4Source(packet []byte) net.IP { 28 return net.IPv4(packet[12], packet[13], packet[14], packet[15]) 29 } 30 31 func SetIPv4Source(packet []byte, source net.IP) { 32 copy(packet[12:16], source.To4()) 33 } 34 35 func IPv4Destination(packet []byte) net.IP { 36 return net.IPv4(packet[16], packet[17], packet[18], packet[19]) 37 } 38 39 func SetIPv4Destination(packet []byte, dest net.IP) { 40 copy(packet[16:20], dest.To4()) 41 } 42 43 func IPv4Payload(packet []byte) []byte { 44 ihl := packet[0] & 0x0F 45 return packet[ihl*4:] 46 } 47 48 // For TCP/UDP 49 func IPv4SourcePort(packet []byte) uint16 { 50 payload := IPv4Payload(packet) 51 return (uint16(payload[0]) << 8) | uint16(payload[1]) 52 } 53 54 func IPv4DestinationPort(packet []byte) uint16 { 55 payload := IPv4Payload(packet) 56 return (uint16(payload[2]) << 8) | uint16(payload[3]) 57 } 58 59 func SetIPv4SourcePort(packet []byte, port uint16) { 60 payload := IPv4Payload(packet) 61 payload[0] = byte(port >> 8) 62 payload[1] = byte(port & 0xFF) 63 } 64 65 func SetIPv4DestinationPort(packet []byte, port uint16) { 66 payload := IPv4Payload(packet) 67 payload[2] = byte(port >> 8) 68 payload[3] = byte(port & 0xFF) 69 }