add proc for serializing IpPackets
This commit is contained in:
parent
4e554b5a83
commit
466d34963b
|
@ -62,6 +62,7 @@ type
|
||||||
var
|
var
|
||||||
ETHERTYPE_IP {.importc: "ETHERTYPE_IP", header: "<netinet/if_ether.h>".}: cushort
|
ETHERTYPE_IP {.importc: "ETHERTYPE_IP", header: "<netinet/if_ether.h>".}: cushort
|
||||||
IPPROTO_TCP {.importc: "IPPROTO_TCP", header: "<netinet/in.h>".}: cint
|
IPPROTO_TCP {.importc: "IPPROTO_TCP", header: "<netinet/in.h>".}: cint
|
||||||
|
TH_SYN {.importc: "TH_SYN", header: "<netinet/tcp.h>".}: uint8
|
||||||
|
|
||||||
proc parseEthernetPacket*(input: string): IpPacket =
|
proc parseEthernetPacket*(input: string): IpPacket =
|
||||||
let etherHeader = cast[ptr Ether_header](input.cstring)
|
let etherHeader = cast[ptr Ether_header](input.cstring)
|
||||||
|
@ -85,3 +86,34 @@ proc parseEthernetPacket*(input: string): IpPacket =
|
||||||
result = IpPacket(protocol: other)
|
result = IpPacket(protocol: other)
|
||||||
else:
|
else:
|
||||||
result = IpPacket(protocol: other)
|
result = IpPacket(protocol: other)
|
||||||
|
|
||||||
|
proc serialize*(packet: IpPacket): string =
|
||||||
|
case packet.protocol
|
||||||
|
of tcp:
|
||||||
|
let srcIp = InAddr(s_addr: htonl(cast[uint32](packet.tcpIpSrc.address_v4)))
|
||||||
|
let dstIp = InAddr(s_addr: htonl(cast[uint32](packet.tcpIpDst.address_v4)))
|
||||||
|
var ipHeader = Ip(ip_hl: 5,
|
||||||
|
ip_v: 4,
|
||||||
|
ip_tos: 0,
|
||||||
|
ip_len: htons(40),
|
||||||
|
ip_id: htons(54321), # FIXME: random number
|
||||||
|
ip_off: 0,
|
||||||
|
ip_ttl: 64,
|
||||||
|
ip_p: 6.cuchar,
|
||||||
|
ip_sum: htons(0), # done by kernel
|
||||||
|
ip_src: srcIp,
|
||||||
|
ip_dst: dstIp)
|
||||||
|
var tcpHeader = Tcphdr(th_sport: htons(packet.tcpPortSrc.uint16),
|
||||||
|
th_dport: htons(packet.tcpPortDst.uint16),
|
||||||
|
th_seq: htonl(packet.tcpSeqNumber),
|
||||||
|
th_ack: 0,
|
||||||
|
th_off: 5,
|
||||||
|
th_flags: TH_SYN,
|
||||||
|
th_win: 1452 * 10,
|
||||||
|
th_sum: 0,
|
||||||
|
th_urp: 0)
|
||||||
|
result = newString(sizeof(Ip) + sizeof(Tcphdr))
|
||||||
|
copyMem(addr result[0], addr ipHeader, sizeof(Ip))
|
||||||
|
copyMem(addr result[sizeof(Ip)], addr tcpHeader, sizeof(Tcphdr))
|
||||||
|
else:
|
||||||
|
raise newException(ValueError, "protocol not supported")
|
||||||
|
|
Loading…
Reference in New Issue