diff --git a/mininet/node.py b/mininet/node.py index b197a5b..b33346c 100644 --- a/mininet/node.py +++ b/mininet/node.py @@ -752,28 +752,32 @@ class Switch( Node ): dpidLen = 16 # digits in dpid passed to switch def __init__( self, name, dpid=None, opts='', listenPort=None, **params): - """dpid: dpid for switch (or None to derive from name, e.g. s1 -> 1) + """dpid: dpid hex string (or None to derive from name, e.g. s1 -> 1) opts: additional switch options listenPort: port to listen on for dpctl connections""" Node.__init__( self, name, **params ) - self.dpid = ( ( '0' * self.dpidLen + dpid.translate( None, ':' ) ) - [ -self.dpidLen: ] if dpid else self.defaultDpid() ) + self.dpid = self.defaultDpid( dpid ) self.opts = opts self.listenPort = listenPort if not self.inNamespace: self.controlIntf = Intf( 'lo', self, port=0 ) - def defaultDpid( self ): - "Derive dpid from switch name, s1 -> 1" - try: - dpid = int( re.findall( r'\d+', self.name )[ 0 ] ) - dpid = hex( dpid )[ 2: ] - dpid = '0' * ( self.dpidLen - len( dpid ) ) + dpid - return dpid - except IndexError: - raise Exception( 'Unable to derive default datapath ID - ' - 'please either specify a dpid or use a ' - 'canonical switch name such as s23.' ) + def defaultDpid( self, dpid=None ): + "Return correctly formatted dpid from dpid or switch name (s1 -> 1)" + if dpid: + # Remove any colons and make sure it's a good hex number + dpid = dpid.translate( None, ':' ) + assert len( dpid ) <= self.dpidLen and int( dpid, 16 ) >= 0 + else: + # Use hex of the first number in the switch name + nums = re.findall( r'\d+', self.name ) + if nums: + dpid = hex( int( nums[ 0 ] ) )[ 2: ] + else: + raise Exception( 'Unable to derive default datapath ID - ' + 'please either specify a dpid or use a ' + 'canonical switch name such as s23.' ) + return ( '0' * self.dpidLen + dpid )[ -self.dpidLen : ] def defaultIntf( self ): "Return control interface"