Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/udpsock.go

Documentation: net

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

View as plain text