• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5
6def inet_hwton(hw_addr):
7    """Converts a representation of an Ethernet address to its packed format.
8
9    @param hw_addr: A string representing an Ethernet address in hex format like
10    "BA:C0:11:C0:FF:EE", "BAC011C0FFEE" or already in its binary representation.
11    @return: The 6-byte binary form of the provided Ethernet address.
12    """
13    if len(hw_addr) == 6: # Already in network format.
14        return hw_addr
15    if len(hw_addr) == 12: # Hex format without : in between.
16        return ''.join(chr(int(hw_addr[i:i + 2], 16)) for i in range(0, 12, 2))
17    if len(hw_addr) == 17: # Hex format with : in between.
18        return ''.join(chr(int(hw_addr[i:i + 2], 16)) for i in range(0, 17, 3))
19
20
21def inet_ntohw(packed_hw_addr):
22    """Converts a binary packed Ethernet address to its hex representation.
23
24    @param packed_hw_addr: The 6-byte binary form of the provided Ethernet
25    address.
26    @return: The hex representation as in "AA:BB:CC:00:11:22".
27    """
28    return '%.2X:%.2X:%.2X:%.2X:%.2X:%.2X' % tuple(map(ord, packed_hw_addr))
29