github.com/JohanShen/go-utils@v1.1.4-0.20201117124024-901319a2b2a0/utils/net.go (about)

     1  package utils
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net"
     7  	"os"
     8  	"strings"
     9  )
    10  
    11  func GetMACAddress() (string, error) {
    12  	netInterfaces, err := net.Interfaces()
    13  	if err != nil {
    14  		return "", err
    15  	}
    16  
    17  	if len(netInterfaces) == 0 {
    18  		return "", errors.New("无法获取到正确的MAC地址,网卡数量为空。")
    19  	}
    20  
    21  	str := make([]string, len(netInterfaces))
    22  	for i := 0; i < len(netInterfaces); i++ {
    23  		//fmt.Println(netInterfaces[i])
    24  		if (netInterfaces[i].Flags&net.FlagUp) != 0 && (netInterfaces[i].Flags&net.FlagLoopback) == 0 {
    25  			adds, _ := netInterfaces[i].Addrs()
    26  			for _, address := range adds {
    27  				inet, ok := address.(*net.IPNet)
    28  				//fmt.Println(inet.IP)
    29  				if ok && inet.IP.IsGlobalUnicast() {
    30  					// 如果IP是全局单拨地址,则返回MAC地址
    31  					mac := netInterfaces[i].HardwareAddr.String()
    32  					str[i] = mac
    33  				}
    34  			}
    35  		}
    36  	}
    37  
    38  	return strings.Join(str, "|"), nil
    39  }
    40  
    41  func GetMachineId() string {
    42  	mac, err := GetMACAddress()
    43  	if err != nil {
    44  		mac = ""
    45  	}
    46  	name, err := os.Hostname()
    47  	if err != nil {
    48  		name = "default"
    49  	}
    50  	pid := os.Getpid()
    51  	key := fmt.Sprintf("%v|%v", mac, name)
    52  	val := uint64(HashCode(key)) + uint64(pid)
    53  
    54  	if v, err := Oct2Any(val, 62); err != nil {
    55  		return ""
    56  	} else {
    57  		return v
    58  	}
    59  }