1
2
3
4
5
6
7 package ipv4
8
9 import (
10 "net"
11
12 "golang.org/x/net/internal/socket"
13 )
14
15
16
17
18
19 func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) {
20 if !c.ok() {
21 return 0, nil, nil, errInvalidConn
22 }
23 c.rawOpt.RLock()
24 m := socket.Message{
25 OOB: NewControlMessage(c.rawOpt.cflags),
26 }
27 c.rawOpt.RUnlock()
28 switch c.PacketConn.(type) {
29 case *net.UDPConn:
30 m.Buffers = [][]byte{b}
31 if err := c.RecvMsg(&m, 0); err != nil {
32 return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
33 }
34 case *net.IPConn:
35 h := make([]byte, HeaderLen)
36 m.Buffers = [][]byte{h, b}
37 if err := c.RecvMsg(&m, 0); err != nil {
38 return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
39 }
40 hdrlen := int(h[0]&0x0f) << 2
41 if hdrlen > len(h) {
42 d := hdrlen - len(h)
43 copy(b, b[d:])
44 m.N -= d
45 } else {
46 m.N -= hdrlen
47 }
48 default:
49 return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType}
50 }
51 if m.NN > 0 {
52 if compatFreeBSD32 {
53 adjustFreeBSD32(&m)
54 }
55 cm = new(ControlMessage)
56 if err := cm.Parse(m.OOB[:m.NN]); err != nil {
57 return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
58 }
59 cm.Src = netAddrToIP4(m.Addr)
60 }
61 return m.N, cm, m.Addr, nil
62 }
63
64
65
66
67
68
69
70 func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) {
71 if !c.ok() {
72 return 0, errInvalidConn
73 }
74 m := socket.Message{
75 Buffers: [][]byte{b},
76 OOB: cm.Marshal(),
77 Addr: dst,
78 }
79 err = c.SendMsg(&m, 0)
80 if err != nil {
81 err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err}
82 }
83 return m.N, err
84 }
85
View as plain text