blob: 66349a3c19a6ebd8aff8df74acc6e90c4837dd11 [file] [log] [blame]
Renato Botelho do Coutoead1e532019-10-31 13:31:07 -05001#!/usr/bin/env python3
Ole Troan8006c6a2018-12-17 12:02:26 +01002#
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
17import binascii
18
19
20def mac_pton(s):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020021 """Convert MAC address as text to binary"""
22 return binascii.unhexlify(s.replace(":", ""))
Ole Troan8006c6a2018-12-17 12:02:26 +010023
24
25def mac_ntop(binary):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020026 """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"))
Ole Troan8006c6a2018-12-17 12:02:26 +010029
30
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020031class MACAddress:
Ole Troan8006c6a2018-12-17 12:02:26 +010032 def __init__(self, mac):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020033 """MAC Address as a text-string (aa:bb:cc:dd:ee:ff) or 6 bytes"""
Ole Troan8006c6a2018-12-17 12:02:26 +010034 # Of course Python 2 doesn't distinguish str from bytes
35 if type(mac) is bytes and len(mac) == 6:
36 self.mac_binary = mac
37 self.mac_string = mac_ntop(mac)
38 else:
39 self.mac_binary = mac_pton(mac)
40 self.mac_string = mac
41
42 @property
43 def packed(self):
44 return self.mac_binary
45
46 def __len__(self):
47 return 6
48
49 def __str__(self):
50 return self.mac_string
51
52 def __repr__(self):
Klement Sekerad9b0c6f2022-04-26 19:02:15 +020053 return "%s(%s)" % (self.__class__.__name__, self.mac_string)
Paul Vinciguerrafe4827c2018-12-26 15:27:10 -080054
55 def __eq__(self, other):
56 if not isinstance(other, MACAddress):
Paul Vinciguerra6af62562019-11-12 12:11:00 -050057 try:
58 # if it looks like a mac address, we'll take it.
59 # (allows for equality with scapy hw-addresses)
60 return self.mac_binary == MACAddress(other).mac_binary
61 except Exception:
62 return NotImplemented
Paul Vinciguerrafe4827c2018-12-26 15:27:10 -080063 return self.mac_binary == other.mac_binary
64
65 def __ne__(self, other):
66 return not self == other
67
68 def __hash__(self):
69 return hash(self.mac_binary)