Created
December 19, 2016 17:28
-
-
Save eugeneia/d95a9c096183c2d9a886aec580370c39 to your computer and use it in GitHub Desktop.
packet templates with and without lib.protocol.datagram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ethernet = require("lib.protocol.ethernet") | |
MyApp = {} | |
function MyApp:new () | |
local o = {} | |
o.pkt = packet.allocate() | |
-- create a header that points into o.pkt | |
o.eth = ethernet:new_from_mem(o.pkt.data, ethernet:sizeof()) | |
-- initialize all static fields, unintialized fields will be garbage | |
o.eth:src(ethernet:pton("42:00:00:00:00:42")) | |
-- ... | |
return setmetatable(o, {__index=MyApp}) | |
end | |
function MyApp:echo (p_in) | |
local in_eth = ethernet:new_from_mem(p_in.data, ethernet:sizeof()) | |
-- modify self.pkt's ethernet header based on p | |
self.eth:dst(in_eth:src()) | |
-- copy payload to self.pkt | |
self.pkt.length = ethernet:sizeof() | |
packet.append(self.pkt, | |
p_in.data + ethernet:sizeof(), | |
p_in.length - ethernet:sizeof()) | |
-- return the packet to transmit | |
return packet.clone(self.pkt) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ethernet = require("lib.protocol.ethernet") | |
local datagram = require("lib.protocol.datagram") | |
MyApp = {} | |
function MyApp:new () | |
local o = {} | |
o.out_dgram = datagram:new() -- calls packet.allocate internally | |
-- push a new header, unspecified fields have sensible defaults. | |
o.out_dgram:push(ethernet:new({src=ethernet:pton("42:00:00:00:00:42")})) | |
-- "reset" datagram to the beginning of our template (datagram instances | |
-- have a new() method that reuses the instance) | |
o.out_dgram:new(o.out_dgram:packet()) | |
-- so we can overlay a header into the packet | |
o.out_eth = dgram:parse_match(ethernet) | |
-- allocate extra datagram and ethernet header instances for parsing to | |
-- avoid allocation in MyApp:echo | |
o.in_dgram = datagram:new() | |
packet.free(o.in_dgram:packet()) -- don't need it | |
o.in_eth = ethernet:new({}) | |
return setmetatable(o, {__index=MyApp}) | |
end | |
function MyApp:echo (p_in) | |
local in_gram, in_eth = self.in_dgram, self.in_eth | |
local out_gram, out_eth = self.out_dgram, self.out_eth | |
-- parse | |
in_dgram:new(p_in) | |
in_dgram:parse_match(in_eth) | |
-- copy | |
out_eth:dst(in_eth:src()) | |
out_dgram:payload(in_dgram:data()) | |
return packet.clone(out_dgram:packet()) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment