3 # Copyright (c) 2016 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
21 """Convert MAC address as text to binary"""
22 return binascii.unhexlify(s.replace(":", ""))
26 """Convert MAC address as binary to text"""
27 x = b":".join(binascii.hexlify(binary)[i : i + 2] for i in range(0, 12, 2))
28 return str(x.decode("ascii"))
32 def __init__(self, mac):
33 """MAC Address as a text-string (aa:bb:cc:dd:ee:ff) or 6 bytes"""
34 # Of course Python 2 doesn't distinguish str from bytes
35 if type(mac) is bytes and len(mac) == 6:
37 self.mac_string = mac_ntop(mac)
39 self.mac_binary = mac_pton(mac)
44 return self.mac_binary
50 return self.mac_string
53 return "%s(%s)" % (self.__class__.__name__, self.mac_string)
55 def __eq__(self, other):
57 if not isinstance(other, MACAddress):
59 # if it looks like a mac address, we'll take it.
60 # (allows for equality with scapy hw-addresses)
61 return self.mac_binary == MACAddress(other).mac_binary
64 return self.mac_binary == other.mac_binary
66 def __ne__(self, other):
67 return not self == other
70 return hash(self.mac_binary)