forked from zimbatm/socketmaster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listen.go
68 lines (56 loc) · 1.3 KB
/
listen.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
package main
import (
"fmt"
"net"
"net/url"
"os"
"strconv"
"syscall"
)
// Utility to open a tcp[46]? or fd
func ListenFile(rawurl string) (file *os.File, err error) {
u, err := url.Parse(rawurl)
if err != nil {
return
}
switch u.Scheme {
case "fd":
var fd uint64
fd, err = strconv.ParseUint(u.Host, 10, 8)
if err != nil {
return
}
// NOTE: The name argument doesn't really matter apparently
file = os.NewFile(uintptr(fd), fmt.Sprintf("fd://%d", fd))
case "unix": //, "unixpacket", "unixgram":
var laddr *net.UnixAddr
var listener *net.UnixListener
laddr, err = net.ResolveUnixAddr(u.Scheme, u.Path)
if err != nil {
return
}
listener, err = net.ListenUnix(u.Scheme, laddr)
if err != nil {
return
}
file, err = listener.File()
case "tcp", "tcp4", "tcp6":
var laddr *net.TCPAddr
var listener *net.TCPListener
laddr, err = net.ResolveTCPAddr(u.Scheme, u.Host)
if err != nil {
return
}
listener, err = net.ListenTCP(u.Scheme, laddr)
if err != nil {
return
}
// Closing the listener doesn't affect the file and reversely.
// http://golang.org/pkg/net/#TCPListener.File
file, err = listener.File()
syscall.SetsockoptInt(int(file.Fd()), syscall.SOL_SOCKET, 0x0F, 1)
default:
err = fmt.Errorf("Unsupported scheme: %s", u.Scheme)
}
return
}