Created
December 27, 2012 13:52
-
-
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.
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
#!/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