-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello.go
89 lines (76 loc) · 1.87 KB
/
hello.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package mobile
import (
"fmt"
"log"
"net"
"net/netip"
"github.com/wlynxg/anet"
)
func Greetings(name string) string {
allifaces, err := anet.Interfaces()
if err != nil {
return fmt.Sprintf("Error: %s!", err)
}
s := ""
for _, iface := range allifaces {
s = ""
s += iface.Name
_, err := net.InterfaceByName(s)
if err != nil {
log.Printf("net: interface name %s not found, error %s", s, err)
}
addrs, err := anet.InterfaceAddrsByInterface(&iface)
if err != nil {
s += fmt.Sprintf("Error: %s", err) + "\n"
} else {
s += fmt.Sprintf("%s \n", addrs)
}
for _, addr := range addrs {
parseAddr, err := netip.ParsePrefix(addr.String())
if err != nil {
continue
}
if parseAddr.Addr().Is4() || parseAddr.Addr().IsMulticast() {
continue
}
addr := fmt.Sprintf("[%s%%%s]:51234", parseAddr.Addr().String(), iface.Name)
l, err := net.Listen("tcp", addr)
if err != nil {
log.Printf("listen %s error: %s", addr, err)
continue
}
// Start accepting connections in a new goroutine
go acceptConnections(l)
// Test the listener by dialing it
dialer := &net.Dialer{}
addrIP, _, _ := net.ParseCIDR(parseAddr.Addr().String())
dialer.LocalAddr = &net.TCPAddr{
IP: addrIP,
Port: 0,
Zone: iface.Name,
}
_, err = dialer.Dial("tcp", addr)
if err != nil {
log.Printf("dial %s error: %s", dialer, err)
}
}
}
return fmt.Sprintf("Hello, %s!", s)
}
func acceptConnections(l net.Listener) {
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Printf("accept error: %s", err)
continue
}
// Handle connection in a new goroutine.
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Implement your connection handling logic here
log.Printf("Handling connection from %s", conn.RemoteAddr().String())
}