Renato Botelho do Couto | ead1e53 | 2019-10-31 13:31:07 -0500 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Ole Troan | 8006c6a | 2018-12-17 12:02:26 +0100 | [diff] [blame] | 2 | # |
| 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: |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 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. |
| 15 | # |
| 16 | |
| 17 | import binascii |
| 18 | |
| 19 | |
| 20 | def mac_pton(s): |
| 21 | '''Convert MAC address as text to binary''' |
| 22 | return binascii.unhexlify(s.replace(':', '')) |
| 23 | |
| 24 | |
| 25 | def mac_ntop(binary): |
| 26 | '''Convert MAC address as binary to text''' |
| 27 | x = b':'.join(binascii.hexlify(binary)[i:i + 2] |
| 28 | for i in range(0, 12, 2)) |
| 29 | return str(x.decode('ascii')) |
| 30 | |
| 31 | |
| 32 | class MACAddress(): |
| 33 | def __init__(self, mac): |
| 34 | '''MAC Address as a text-string (aa:bb:cc:dd:ee:ff) or 6 bytes''' |
| 35 | # Of course Python 2 doesn't distinguish str from bytes |
| 36 | if type(mac) is bytes and len(mac) == 6: |
| 37 | self.mac_binary = mac |
| 38 | self.mac_string = mac_ntop(mac) |
| 39 | else: |
| 40 | self.mac_binary = mac_pton(mac) |
| 41 | self.mac_string = mac |
| 42 | |
| 43 | @property |
| 44 | def packed(self): |
| 45 | return self.mac_binary |
| 46 | |
| 47 | def __len__(self): |
| 48 | return 6 |
| 49 | |
| 50 | def __str__(self): |
| 51 | return self.mac_string |
| 52 | |
| 53 | def __repr__(self): |
| 54 | return '%s(%s)' % (self.__class__.__name__, self.mac_string) |
Paul Vinciguerra | fe4827c | 2018-12-26 15:27:10 -0800 | [diff] [blame] | 55 | |
| 56 | def __eq__(self, other): |
Paul Vinciguerra | 6af6256 | 2019-11-12 12:11:00 -0500 | [diff] [blame] | 57 | |
Paul Vinciguerra | fe4827c | 2018-12-26 15:27:10 -0800 | [diff] [blame] | 58 | if not isinstance(other, MACAddress): |
Paul Vinciguerra | 6af6256 | 2019-11-12 12:11:00 -0500 | [diff] [blame] | 59 | try: |
| 60 | # if it looks like a mac address, we'll take it. |
| 61 | # (allows for equality with scapy hw-addresses) |
| 62 | return self.mac_binary == MACAddress(other).mac_binary |
| 63 | except Exception: |
| 64 | return NotImplemented |
Paul Vinciguerra | fe4827c | 2018-12-26 15:27:10 -0800 | [diff] [blame] | 65 | return self.mac_binary == other.mac_binary |
| 66 | |
| 67 | def __ne__(self, other): |
| 68 | return not self == other |
| 69 | |
| 70 | def __hash__(self): |
| 71 | return hash(self.mac_binary) |