-
Notifications
You must be signed in to change notification settings - Fork 15
/
listener.go
83 lines (71 loc) · 1.75 KB
/
listener.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
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* HTTP listener
*/
package main
import (
"net"
"strconv"
"time"
)
// Listener wraps net.Listener
//
// Note, if IP address is not specified, go stdlib
// creates a beautiful listener, able to listen to
// IPv4 and IPv6 simultaneously. But it cannot do it,
// if IP address is given
//
// So it is much simpler to always create a broadcast listener
// and to filter incoming connection in Accept() wrapper rather
// that create separate IPv4 and IPv6 listeners and dial with
// them both
type Listener struct {
net.Listener // Underlying net.Listener
}
// NewListener creates new listener
func NewListener(port int) (net.Listener, error) {
// Setup network and address
network := "tcp4"
if Conf.IPV6Enable {
network = "tcp"
}
addr := ":" + strconv.Itoa(port)
// Create net.Listener
nl, err := net.Listen(network, addr)
if err != nil {
return nil, err
}
// Wrap into Listener
return Listener{nl}, nil
}
// Accept new connection
func (l Listener) Accept() (net.Conn, error) {
for {
// Accept new connection
conn, err := l.Listener.Accept()
if err != nil {
return nil, err
}
// Obtain underlying net.TCPConn
tcpconn, ok := conn.(*net.TCPConn)
if !ok {
// Should never happen, actually
conn.Close()
continue
}
// Reject non-loopback connections, if required
if Conf.LoopbackOnly &&
!tcpconn.LocalAddr().(*net.TCPAddr).IP.IsLoopback() {
tcpconn.SetLinger(0)
tcpconn.Close()
continue
}
// Setup TCP parameters
tcpconn.SetKeepAlive(true)
tcpconn.SetKeepAlivePeriod(20 * time.Second)
return tcpconn, nil
}
}