udpsock.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package net
  5. import (
  6. "context"
  7. "internal/itoa"
  8. "net/netip"
  9. "syscall"
  10. )
  11. // BUG(mikio): On Plan 9, the ReadMsgUDP and
  12. // WriteMsgUDP methods of UDPConn are not implemented.
  13. // BUG(mikio): On Windows, the File method of UDPConn is not
  14. // implemented.
  15. // BUG(mikio): On JS, methods and functions related to UDPConn are not
  16. // implemented.
  17. // UDPAddr represents the address of a UDP end point.
  18. type UDPAddr struct {
  19. IP IP
  20. Port int
  21. Zone string // IPv6 scoped addressing zone
  22. }
  23. // AddrPort returns the UDPAddr a as a netip.AddrPort.
  24. //
  25. // If a.Port does not fit in a uint16, it's silently truncated.
  26. //
  27. // If a is nil, a zero value is returned.
  28. func (a *UDPAddr) AddrPort() netip.AddrPort {
  29. if a == nil {
  30. return netip.AddrPort{}
  31. }
  32. na, _ := netip.AddrFromSlice(a.IP)
  33. na = na.WithZone(a.Zone)
  34. return netip.AddrPortFrom(na, uint16(a.Port))
  35. }
  36. // Network returns the address's network name, "udp".
  37. func (a *UDPAddr) Network() string { return "udp" }
  38. func (a *UDPAddr) String() string {
  39. if a == nil {
  40. return "<nil>"
  41. }
  42. ip := ipEmptyString(a.IP)
  43. if a.Zone != "" {
  44. return JoinHostPort(ip+"%"+a.Zone, itoa.Itoa(a.Port))
  45. }
  46. return JoinHostPort(ip, itoa.Itoa(a.Port))
  47. }
  48. func (a *UDPAddr) isWildcard() bool {
  49. if a == nil || a.IP == nil {
  50. return true
  51. }
  52. return a.IP.IsUnspecified()
  53. }
  54. func (a *UDPAddr) opAddr() Addr {
  55. if a == nil {
  56. return nil
  57. }
  58. return a
  59. }
  60. // ResolveUDPAddr returns an address of UDP end point.
  61. //
  62. // The network must be a UDP network name.
  63. //
  64. // If the host in the address parameter is not a literal IP address or
  65. // the port is not a literal port number, ResolveUDPAddr resolves the
  66. // address to an address of UDP end point.
  67. // Otherwise, it parses the address as a pair of literal IP address
  68. // and port number.
  69. // The address parameter can use a host name, but this is not
  70. // recommended, because it will return at most one of the host name's
  71. // IP addresses.
  72. //
  73. // See func Dial for a description of the network and address
  74. // parameters.
  75. func ResolveUDPAddr(network, address string) (*UDPAddr, error) {
  76. switch network {
  77. case "udp", "udp4", "udp6":
  78. case "": // a hint wildcard for Go 1.0 undocumented behavior
  79. network = "udp"
  80. default:
  81. return nil, UnknownNetworkError(network)
  82. }
  83. addrs, err := DefaultResolver.internetAddrList(context.Background(), network, address)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return addrs.forResolve(network, address).(*UDPAddr), nil
  88. }
  89. // UDPAddrFromAddrPort returns addr as a UDPAddr. If addr.IsValid() is false,
  90. // then the returned UDPAddr will contain a nil IP field, indicating an
  91. // address family-agnostic unspecified address.
  92. func UDPAddrFromAddrPort(addr netip.AddrPort) *UDPAddr {
  93. return &UDPAddr{
  94. IP: addr.Addr().AsSlice(),
  95. Zone: addr.Addr().Zone(),
  96. Port: int(addr.Port()),
  97. }
  98. }
  99. // An addrPortUDPAddr is a netip.AddrPort-based UDP address that satisfies the Addr interface.
  100. type addrPortUDPAddr struct {
  101. netip.AddrPort
  102. }
  103. func (addrPortUDPAddr) Network() string { return "udp" }
  104. // UDPConn is the implementation of the Conn and PacketConn interfaces
  105. // for UDP network connections.
  106. type UDPConn struct {
  107. conn
  108. }
  109. // SyscallConn returns a raw network connection.
  110. // This implements the syscall.Conn interface.
  111. func (c *UDPConn) SyscallConn() (syscall.RawConn, error) {
  112. if !c.ok() {
  113. return nil, syscall.EINVAL
  114. }
  115. return newRawConn(c.fd)
  116. }
  117. // ReadFromUDP acts like ReadFrom but returns a UDPAddr.
  118. func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) {
  119. // This function is designed to allow the caller to control the lifetime
  120. // of the returned *UDPAddr and thereby prevent an allocation.
  121. // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/.
  122. // The real work is done by readFromUDP, below.
  123. return c.readFromUDP(b, &UDPAddr{})
  124. }
  125. // readFromUDP implements ReadFromUDP.
  126. func (c *UDPConn) readFromUDP(b []byte, addr *UDPAddr) (int, *UDPAddr, error) {
  127. if !c.ok() {
  128. return 0, nil, syscall.EINVAL
  129. }
  130. n, addr, err := c.readFrom(b, addr)
  131. if err != nil {
  132. err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  133. }
  134. return n, addr, err
  135. }
  136. // ReadFrom implements the PacketConn ReadFrom method.
  137. func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error) {
  138. n, addr, err := c.readFromUDP(b, &UDPAddr{})
  139. if addr == nil {
  140. // Return Addr(nil), not Addr(*UDPConn(nil)).
  141. return n, nil, err
  142. }
  143. return n, addr, err
  144. }
  145. // ReadFromUDPAddrPort acts like ReadFrom but returns a netip.AddrPort.
  146. func (c *UDPConn) ReadFromUDPAddrPort(b []byte) (n int, addr netip.AddrPort, err error) {
  147. if !c.ok() {
  148. return 0, netip.AddrPort{}, syscall.EINVAL
  149. }
  150. n, addr, err = c.readFromAddrPort(b)
  151. if err != nil {
  152. err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  153. }
  154. return n, addr, err
  155. }
  156. // ReadMsgUDP reads a message from c, copying the payload into b and
  157. // the associated out-of-band data into oob. It returns the number of
  158. // bytes copied into b, the number of bytes copied into oob, the flags
  159. // that were set on the message and the source address of the message.
  160. //
  161. // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
  162. // used to manipulate IP-level socket options in oob.
  163. func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error) {
  164. var ap netip.AddrPort
  165. n, oobn, flags, ap, err = c.ReadMsgUDPAddrPort(b, oob)
  166. if ap.IsValid() {
  167. addr = UDPAddrFromAddrPort(ap)
  168. }
  169. return
  170. }
  171. // ReadMsgUDPAddrPort is like ReadMsgUDP but returns an netip.AddrPort instead of a UDPAddr.
  172. func (c *UDPConn) ReadMsgUDPAddrPort(b, oob []byte) (n, oobn, flags int, addr netip.AddrPort, err error) {
  173. if !c.ok() {
  174. return 0, 0, 0, netip.AddrPort{}, syscall.EINVAL
  175. }
  176. n, oobn, flags, addr, err = c.readMsg(b, oob)
  177. if err != nil {
  178. err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  179. }
  180. return
  181. }
  182. // WriteToUDP acts like WriteTo but takes a UDPAddr.
  183. func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error) {
  184. if !c.ok() {
  185. return 0, syscall.EINVAL
  186. }
  187. n, err := c.writeTo(b, addr)
  188. if err != nil {
  189. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err}
  190. }
  191. return n, err
  192. }
  193. // WriteToUDPAddrPort acts like WriteTo but takes a netip.AddrPort.
  194. func (c *UDPConn) WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error) {
  195. if !c.ok() {
  196. return 0, syscall.EINVAL
  197. }
  198. n, err := c.writeToAddrPort(b, addr)
  199. if err != nil {
  200. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addrPortUDPAddr{addr}, Err: err}
  201. }
  202. return n, err
  203. }
  204. // WriteTo implements the PacketConn WriteTo method.
  205. func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error) {
  206. if !c.ok() {
  207. return 0, syscall.EINVAL
  208. }
  209. a, ok := addr.(*UDPAddr)
  210. if !ok {
  211. return 0, &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr, Err: syscall.EINVAL}
  212. }
  213. n, err := c.writeTo(b, a)
  214. if err != nil {
  215. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: a.opAddr(), Err: err}
  216. }
  217. return n, err
  218. }
  219. // WriteMsgUDP writes a message to addr via c if c isn't connected, or
  220. // to c's remote address if c is connected (in which case addr must be
  221. // nil). The payload is copied from b and the associated out-of-band
  222. // data is copied from oob. It returns the number of payload and
  223. // out-of-band bytes written.
  224. //
  225. // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be
  226. // used to manipulate IP-level socket options in oob.
  227. func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error) {
  228. if !c.ok() {
  229. return 0, 0, syscall.EINVAL
  230. }
  231. n, oobn, err = c.writeMsg(b, oob, addr)
  232. if err != nil {
  233. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err}
  234. }
  235. return
  236. }
  237. // WriteMsgUDPAddrPort is like WriteMsgUDP but takes a netip.AddrPort instead of a UDPAddr.
  238. func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error) {
  239. if !c.ok() {
  240. return 0, 0, syscall.EINVAL
  241. }
  242. n, oobn, err = c.writeMsgAddrPort(b, oob, addr)
  243. if err != nil {
  244. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addrPortUDPAddr{addr}, Err: err}
  245. }
  246. return
  247. }
  248. func newUDPConn(fd *netFD) *UDPConn { return &UDPConn{conn{fd}} }
  249. // DialUDP acts like Dial for UDP networks.
  250. //
  251. // The network must be a UDP network name; see func Dial for details.
  252. //
  253. // If laddr is nil, a local address is automatically chosen.
  254. // If the IP field of raddr is nil or an unspecified IP address, the
  255. // local system is assumed.
  256. func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error) {
  257. switch network {
  258. case "udp", "udp4", "udp6":
  259. default:
  260. return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: UnknownNetworkError(network)}
  261. }
  262. if raddr == nil {
  263. return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
  264. }
  265. sd := &sysDialer{network: network, address: raddr.String()}
  266. c, err := sd.dialUDP(context.Background(), laddr, raddr)
  267. if err != nil {
  268. return nil, &OpError{Op: "dial", Net: network, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
  269. }
  270. return c, nil
  271. }
  272. // ListenUDP acts like ListenPacket for UDP networks.
  273. //
  274. // The network must be a UDP network name; see func Dial for details.
  275. //
  276. // If the IP field of laddr is nil or an unspecified IP address,
  277. // ListenUDP listens on all available IP addresses of the local system
  278. // except multicast IP addresses.
  279. // If the Port field of laddr is 0, a port number is automatically
  280. // chosen.
  281. func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error) {
  282. switch network {
  283. case "udp", "udp4", "udp6":
  284. default:
  285. return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(network)}
  286. }
  287. if laddr == nil {
  288. laddr = &UDPAddr{}
  289. }
  290. sl := &sysListener{network: network, address: laddr.String()}
  291. c, err := sl.listenUDP(context.Background(), laddr)
  292. if err != nil {
  293. return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: laddr.opAddr(), Err: err}
  294. }
  295. return c, nil
  296. }
  297. // ListenMulticastUDP acts like ListenPacket for UDP networks but
  298. // takes a group address on a specific network interface.
  299. //
  300. // The network must be a UDP network name; see func Dial for details.
  301. //
  302. // ListenMulticastUDP listens on all available IP addresses of the
  303. // local system including the group, multicast IP address.
  304. // If ifi is nil, ListenMulticastUDP uses the system-assigned
  305. // multicast interface, although this is not recommended because the
  306. // assignment depends on platforms and sometimes it might require
  307. // routing configuration.
  308. // If the Port field of gaddr is 0, a port number is automatically
  309. // chosen.
  310. //
  311. // ListenMulticastUDP is just for convenience of simple, small
  312. // applications. There are golang.org/x/net/ipv4 and
  313. // golang.org/x/net/ipv6 packages for general purpose uses.
  314. //
  315. // Note that ListenMulticastUDP will set the IP_MULTICAST_LOOP socket option
  316. // to 0 under IPPROTO_IP, to disable loopback of multicast packets.
  317. func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error) {
  318. switch network {
  319. case "udp", "udp4", "udp6":
  320. default:
  321. return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: UnknownNetworkError(network)}
  322. }
  323. if gaddr == nil || gaddr.IP == nil {
  324. return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: errMissingAddress}
  325. }
  326. sl := &sysListener{network: network, address: gaddr.String()}
  327. c, err := sl.listenMulticastUDP(context.Background(), ifi, gaddr)
  328. if err != nil {
  329. return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: err}
  330. }
  331. return c, nil
  332. }