Skip to content

Instantly share code, notes, and snippets.

@Crapworks
Created December 27, 2012 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Crapworks/4388517 to your computer and use it in GitHub Desktop.
Save Crapworks/4388517 to your computer and use it in GitHub Desktop.
My first steps into python metaprogramming. Not sure if this really makes sense, but at least it was reasonable for me.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from struct import pack, unpack
from binascii import hexlify, unhexlify
class HWAddr(object):
fmt = "6s"
def __init__(self, addr="FF:FF:FF:FF:FF:FF"):
self.addr = addr
def asc2hex(self):
return unhexlify(self.addr.replace(':',''))
class MetaClass(type):
def __new__(cls, clsname, clsbase, clsdict):
tmp = type.__new__(cls, clsname, clsbase, clsdict)
tmp.__hdr__ = []
for key, val in clsdict.iteritems():
if isinstance(val, HWAddr):
tmp.__hdr__.append((val.asc2hex(), val.fmt))
tmp.__fmt__ = getattr(tmp, '__byte_order__', '>') + ''.join([val[1] for val in tmp.__hdr__])
return tmp
class Packet(object):
__metaclass__ = MetaClass
def __str__(self):
return pack(self.__fmt__, *[ hdr[0] for hdr in self.__hdr__ ])
class Ethernet(Packet):
src = HWAddr("AA:BB:CC:DD:EE:FF")
dst = HWAddr("11:22:33:44:55:66")
if __name__ == '__main__':
print Ethernet()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment