forked from aykevl/plaincast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
64 lines (55 loc) · 1.41 KB
/
util.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
62
63
64
package server
import (
"errors"
"net"
"net/http"
"github.com/nu7hatch/gouuid"
)
// getLocalAddr gets the local address from the specified address.
// It does not truly open a connection (udp doesn't know connections).
func getLocalAddr(req *http.Request) net.Addr {
raddr, err := net.ResolveUDPAddr("udp", req.RemoteAddr)
if err != nil {
panic(err)
}
conn, err := net.DialUDP("udp", nil, raddr)
if err != nil {
panic(err)
}
defer conn.Close()
return conn.LocalAddr()
}
// getUrlIP formats the address so it can be used inside an URL.
// It wraps the IP address inside [ and ] when it's an IPv6 address.
func getUrlIP(addr net.Addr) string {
var ip net.IP
switch addr.(type) {
case *net.UDPAddr:
ip = addr.(*net.UDPAddr).IP
default:
panic("unknown address type")
}
addrString := ip.String()
if ip.To4() == nil {
// IPv6
addrString = "[" + addrString + "]"
}
return addrString
}
// getUUID returns a stable UUID based on the first MAC address
func getUUID() (*uuid.UUID, error) {
itfs, err := net.Interfaces()
if err != nil {
return nil, err
}
// get the first interface with a MAC address
for _, itf := range itfs {
if len(itf.HardwareAddr) == 0 {
continue
}
// this may not be how UUIDv5 is meant to be used...
id := []byte(itf.HardwareAddr.String() + "-" + NAME)
return uuid.NewV5(uuid.NamespaceOID, id)
}
return nil, errors.New("could not find interface with MAC address")
}