~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to twisted/pair/ethernet.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2006-01-16 19:56:10 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20060116195610-ykmxbia4mnnod9o2
Tags: 2.1.0-0ubuntu2
debian/copyright: Include copyright for python 2.3; some 2.3 files
are included in the upstream tarball, but not in the binary packages.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- test-case-name: twisted.pair.test.test_ethernet -*-
2
 
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3
 
# See LICENSE for details.
4
 
 
5
 
#
6
 
 
7
 
 
8
 
"""Support for working directly with ethernet frames"""
9
 
 
10
 
import struct
11
 
 
12
 
 
13
 
from twisted.internet import protocol
14
 
from twisted.pair import raw
15
 
from twisted.python import components
16
 
from zope.interface import implements
17
 
 
18
 
 
19
 
class IEthernetProtocol(components.Interface):
20
 
    """An interface for protocols that handle Ethernet frames"""
21
 
    def addProto():
22
 
        """Add an IRawPacketProtocol protocol"""
23
 
 
24
 
    def datagramReceived():
25
 
        """An Ethernet frame has been received"""
26
 
 
27
 
class EthernetHeader:
28
 
    def __init__(self, data):
29
 
 
30
 
        (self.dest, self.source, self.proto) \
31
 
                    = struct.unpack("!6s6sH", data[:6+6+2])
32
 
 
33
 
class EthernetProtocol(protocol.AbstractDatagramProtocol):
34
 
 
35
 
    implements(IEthernetProtocol)
36
 
    
37
 
    def __init__(self):
38
 
        self.etherProtos = {}
39
 
 
40
 
    def addProto(self, num, proto):
41
 
        proto = raw.IRawPacketProtocol(proto)
42
 
        if num < 0:
43
 
            raise TypeError, 'Added protocol must be positive or zero'
44
 
        if num >= 2**16:
45
 
            raise TypeError, 'Added protocol must fit in 16 bits'
46
 
        if num not in self.etherProtos:
47
 
            self.etherProtos[num] = []
48
 
        self.etherProtos[num].append(proto)
49
 
 
50
 
    def datagramReceived(self, data, partial=0):
51
 
        header = EthernetHeader(data[:14])
52
 
        for proto in self.etherProtos.get(header.proto, ()):
53
 
            proto.datagramReceived(data=data[14:],
54
 
                                   partial=partial,
55
 
                                   dest=header.dest,
56
 
                                   source=header.source,
57
 
                                   protocol=header.proto)
58
 
 
59
 
components.backwardsCompatImplements(EthernetProtocol)