-
Notifications
You must be signed in to change notification settings - Fork 167
/
main.go
61 lines (52 loc) · 1.27 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"encoding/binary"
"fmt"
"math/rand"
"net"
"strconv"
"strings"
"time"
)
func main() {
spanId := GenerateSpanID(GetLocalIP().String())
traceId := GenerateTraceID(GetLocalIP().String())
fmt.Println("traceId: " + traceId, "spanId: " + spanId)
}
func GenerateSpanID(addr string) string {
strAddr := strings.Split(addr, ":")
ip := strAddr[0]
ipLong, _ := Ip2Long(ip)
times := uint64(time.Now().UnixNano())
spanId := ((times ^ uint64(ipLong)) << 32) | uint64(rand.Int31())
return strconv.FormatUint(spanId, 16)
}
func GenerateTraceID(addr string) string {
strAddr := strings.Split(addr, ":")
ip := strAddr[0]
ipLong, _ := Ip2Long(ip)
times := uint64(time.Now().UnixNano())
traceId := ((times ^ uint64(ipLong)) << 32) | uint64(rand.Int31())
return strconv.FormatUint(traceId, 16)
}
func Ip2Long(ip string) (uint32, error) {
ipAddr, err := net.ResolveIPAddr("ip", ip)
if err != nil {
return 0, err
}
return binary.BigEndian.Uint32(ipAddr.IP.To4()), nil
}
func GetLocalIP() net.IP {
addrs, err := net.InterfaceAddrs()
if err != nil {
return net.IPv4zero
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ip := ipnet.IP.To4(); ip != nil {
return ipnet.IP
}
}
}
return net.IPv4zero
}