forked from tongxin97/noise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
51 lines (39 loc) · 898 Bytes
/
tcp.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
package transport
import (
"github.com/pkg/errors"
"net"
"strconv"
"time"
)
var _ Layer = (*tcp)(nil)
type tcp struct{}
func (t tcp) String() string {
return "tcp"
}
func (t tcp) Listen(host string, port uint16) (net.Listener, error) {
if net.ParseIP(host) == nil {
return nil, errors.Errorf("unable to parse host as IP: %s", host)
}
listener, err := net.Listen("tcp", ":"+strconv.Itoa(int(port)))
if err != nil {
return nil, err
}
return listener, nil
}
func (t tcp) Dial(address string) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", address, 3*time.Second)
if err != nil {
return nil, err
}
return conn, nil
}
func (t tcp) IP(address net.Addr) net.IP {
return address.(*net.TCPAddr).IP
}
func (t tcp) Port(address net.Addr) uint16 {
return uint16(address.(*net.TCPAddr).Port)
}
// NewTCP returns a new tcp instance
func NewTCP() tcp {
return tcp{}
}