talos
32 строки · 1023.0 Байт
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5package nethelpers
6
7import (
8"crypto/sha256"
9"fmt"
10)
11
12const maxLinkNameLength = 15
13
14// VLANLinkName builds a VLAN link name out of the base device name and VLAN ID.
15//
16// The function takes care of the maximum length of the link name.
17func VLANLinkName(base string, vlanID uint16) string {
18// VLAN ID is actually 12-bit, so the allowed values are 0-4095.
19// In ".%d" format, vlanID can be up to 5 characters long.
20if len(base)+5 <= maxLinkNameLength {
21return fmt.Sprintf("%s.%d", base, vlanID)
22}
23
24// If the base name is too long, we need to truncate it, but simply
25// truncating might lead to ambiguous link name, so take some hash of the original
26// name.
27prefix := base[:4]
28
29hash := sha256.Sum256([]byte(base))
30
31return fmt.Sprintf("%s%x.%d", prefix, hash[:(maxLinkNameLength-len(prefix)-5)/2], vlanID)
32}
33