-
Notifications
You must be signed in to change notification settings - Fork 0
/
loopback.go
69 lines (60 loc) · 1.49 KB
/
loopback.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
65
66
67
68
69
// CGo binding for Avahi
//
// Copyright (C) 2024 and up by Alexander Pevzner ([email protected])
// See LICENSE for license terms and conditions
//
// Loopback interface
//
//go:build linux || freebsd
package avahi
import (
"fmt"
"net"
"net/netip"
"sync/atomic"
)
// Cached loopback interface index
var loopback int32 = -1
// loopback addresses
var (
loopbackIP4 = netip.MustParseAddr("127.0.0.1")
loopbackIP6 = netip.MustParseAddr("::1")
)
// Loopback returns index of the loopback network interface.
//
// This function may fail, if [net.Interfaces] fails or there
// is no loopback interface in the response.
//
// As this function is extremely unlikely to fail, you may consider
// using [MustLoopback] instead.
func Loopback() (IfIndex, error) {
// Lookup cache
idx := atomic.LoadInt32(&loopback)
if idx != -1 {
return IfIndex(idx), nil
}
// Consult net.Interfaces
ift, err := net.Interfaces()
if err != nil {
return 0, fmt.Errorf("avahi.Loopback: %w", err)
}
for _, ifi := range ift {
if ifi.Flags&net.FlagLoopback != 0 {
atomic.StoreInt32(&loopback, int32(ifi.Index))
return IfIndex(ifi.Index), nil
}
}
return 0, fmt.Errorf("avahi.Loopback: interface not found")
}
// MustLoopback returns index of the loopback network interface.
//
// This is convenience wrapper around the [Loopback] function. If
// Loopback function fails, MustLoopback panics instead of returning
// the error.
func MustLoopback() IfIndex {
idx, err := Loopback()
if err != nil {
panic(err)
}
return idx
}