github.com/activestate/go@v0.0.0-20170614201249-0b81c023a722/src/net/udpsock.go (about)

     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  	"syscall"
    10  )
    11  
    12  // BUG(mikio): On NaCl, Plan 9 and Windows, the ReadMsgUDP and
    13  // WriteMsgUDP methods of UDPConn are not implemented.
    14  
    15  // BUG(mikio): On Windows, the File method of UDPConn is not
    16  // implemented.
    17  
    18  // BUG(mikio): On NaCl, the ListenMulticastUDP function is not
    19  // implemented.
    20  
    21  // UDPAddr represents the address of a UDP end point.
    22  type UDPAddr struct {
    23  	IP   IP
    24  	Port int
    25  	Zone string // IPv6 scoped addressing zone
    26  }
    27  
    28  // Network returns the address's network name, "udp".
    29  func (a *UDPAddr) Network() string { return "udp" }
    30  
    31  func (a *UDPAddr) String() string {
    32  	if a == nil {
    33  		return "<nil>"
    34  	}
    35  	ip := ipEmptyString(a.IP)
    36  	if a.Zone != "" {
    37  		return JoinHostPort(ip+"%"+a.Zone, itoa(a.Port))
    38  	}
    39  	return JoinHostPort(ip, itoa(a.Port))
    40  }
    41  
    42  func (a *UDPAddr) isWildcard() bool {
    43  	if a == nil || a.IP == nil {
    44  		return true
    45  	}
    46  	return a.IP.IsUnspecified()
    47  }
    48  
    49  func (a *UDPAddr) opAddr() Addr {
    50  	if a == nil {
    51  		return nil
    52  	}
    53  	return a
    54  }
    55  
    56  // ResolveUDPAddr parses addr as a UDP address of the form "host:port"
    57  // or "[ipv6-host%zone]:port" and resolves a pair of domain name and
    58  // port name on the network net, which must be "udp", "udp4" or
    59  // "udp6".  A literal address or host name for IPv6 must be enclosed
    60  // in square brackets, as in "[::1]:80", "[ipv6-host]:http" or
    61  // "[ipv6-host%zone]:80".
    62  //
    63  // Resolving a hostname is not recommended because this returns at most
    64  // one of its IP addresses.
    65  func ResolveUDPAddr(net, addr string) (*UDPAddr, error) {
    66  	switch net {
    67  	case "udp", "udp4", "udp6":
    68  	case "": // a hint wildcard for Go 1.0 undocumented behavior
    69  		net = "udp"
    70  	default:
    71  		return nil, UnknownNetworkError(net)
    72  	}
    73  	addrs, err := DefaultResolver.internetAddrList(context.Background(), net, addr)
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	return addrs.first(isIPv4).(*UDPAddr), nil
    78  }
    79  
    80  // UDPConn is the implementation of the Conn and PacketConn interfaces
    81  // for UDP network connections.
    82  type UDPConn struct {
    83  	conn
    84  }
    85  
    86  // SyscallConn returns a raw network connection.
    87  // This implements the syscall.Conn interface.
    88  func (c *UDPConn) SyscallConn() (syscall.RawConn, error) {
    89  	if !c.ok() {
    90  		return nil, syscall.EINVAL
    91  	}
    92  	return newRawConn(c.fd)
    93  }
    94  
    95  // ReadFromUDP reads a UDP packet from c, copying the payload into b.
    96  // It returns the number of bytes copied into b and the return address
    97  // that was on the packet.
    98  //
    99  // ReadFromUDP can be made to time out and return an error with
   100  // Timeout() == true after a fixed time limit; see SetDeadline and
   101  // SetReadDeadline.
   102  func (c *UDPConn) ReadFromUDP(b []byte) (int, *UDPAddr, error) {
   103  	if !c.ok() {
   104  		return 0, nil, syscall.EINVAL
   105  	}
   106  	n, addr, err := c.readFrom(b)
   107  	if err != nil {
   108  		err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
   109  	}
   110  	return n, addr, err
   111  }
   112  
   113  // ReadFrom implements the PacketConn ReadFrom method.
   114  func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error) {
   115  	if !c.ok() {
   116  		return 0, nil, syscall.EINVAL
   117  	}
   118  	n, addr, err := c.readFrom(b)
   119  	if err != nil {
   120  		err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
   121  	}
   122  	if addr == nil {
   123  		return n, nil, err
   124  	}
   125  	return n, addr, err
   126  }
   127  
   128  // ReadMsgUDP reads a packet from c, copying the payload into b and
   129  // the associated out-of-band data into oob. It returns the number
   130  // of bytes copied into b, the number of bytes copied into oob, the
   131  // flags that were set on the packet and the source address of the
   132  // packet.
   133  func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error) {
   134  	if !c.ok() {
   135  		return 0, 0, 0, nil, syscall.EINVAL
   136  	}
   137  	n, oobn, flags, addr, err = c.readMsg(b, oob)
   138  	if err != nil {
   139  		err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
   140  	}
   141  	return
   142  }
   143  
   144  // WriteToUDP writes a UDP packet to addr via c, copying the payload
   145  // from b.
   146  //
   147  // WriteToUDP can be made to time out and return an error with
   148  // Timeout() == true after a fixed time limit; see SetDeadline and
   149  // SetWriteDeadline. On packet-oriented connections, write timeouts
   150  // are rare.
   151  func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error) {
   152  	if !c.ok() {
   153  		return 0, syscall.EINVAL
   154  	}
   155  	n, err := c.writeTo(b, addr)
   156  	if err != nil {
   157  		err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr.opAddr(), Err: err}
   158  	}
   159  	return n, err
   160  }
   161  
   162  // WriteTo implements the PacketConn WriteTo method.
   163  func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error) {
   164  	if !c.ok() {
   165  		return 0, syscall.EINVAL
   166  	}
   167  	a, ok := addr.(*UDPAddr)
   168  	if !ok {
   169  		return 0, &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: addr, Err: syscall.EINVAL}
   170  	}
   171  	n, err := c.writeTo(b, a)
   172  	if err != nil {
   173  		err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: a.opAddr(), Err: err}
   174  	}
   175  	return n, err
   176  }
   177  
   178  // WriteMsgUDP writes a packet to addr via c if c isn't connected, or
   179  // to c's remote destination address if c is connected (in which case
   180  // addr must be nil).  The payload is copied from b and the associated
   181  // out-of-band data is copied from oob. It returns the number of
   182  // payload and out-of-band bytes written.
   183  func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error) {
   184  	if !c.ok() {
   185  		return 0, 0, syscall.EINVAL
   186  	}
   187  	n, oobn, err = c.writeMsg(b, oob, 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
   192  }
   193  
   194  func newUDPConn(fd *netFD) *UDPConn { return &UDPConn{conn{fd}} }
   195  
   196  // DialUDP connects to the remote address raddr on the network net,
   197  // which must be "udp", "udp4", or "udp6".  If laddr is not nil, it is
   198  // used as the local address for the connection.
   199  func DialUDP(net string, laddr, raddr *UDPAddr) (*UDPConn, error) {
   200  	switch net {
   201  	case "udp", "udp4", "udp6":
   202  	default:
   203  		return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: UnknownNetworkError(net)}
   204  	}
   205  	if raddr == nil {
   206  		return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: nil, Err: errMissingAddress}
   207  	}
   208  	c, err := dialUDP(context.Background(), net, laddr, raddr)
   209  	if err != nil {
   210  		return nil, &OpError{Op: "dial", Net: net, Source: laddr.opAddr(), Addr: raddr.opAddr(), Err: err}
   211  	}
   212  	return c, nil
   213  }
   214  
   215  // ListenUDP listens for incoming UDP packets addressed to the local
   216  // address laddr. Net must be "udp", "udp4", or "udp6".  If laddr has
   217  // a port of 0, ListenUDP will choose an available port.
   218  // The LocalAddr method of the returned UDPConn can be used to
   219  // discover the port. The returned connection's ReadFrom and WriteTo
   220  // methods can be used to receive and send UDP packets with per-packet
   221  // addressing.
   222  func ListenUDP(net string, laddr *UDPAddr) (*UDPConn, error) {
   223  	switch net {
   224  	case "udp", "udp4", "udp6":
   225  	default:
   226  		return nil, &OpError{Op: "listen", Net: net, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(net)}
   227  	}
   228  	if laddr == nil {
   229  		laddr = &UDPAddr{}
   230  	}
   231  	c, err := listenUDP(context.Background(), net, laddr)
   232  	if err != nil {
   233  		return nil, &OpError{Op: "listen", Net: net, Source: nil, Addr: laddr.opAddr(), Err: err}
   234  	}
   235  	return c, nil
   236  }
   237  
   238  // ListenMulticastUDP listens for incoming multicast UDP packets
   239  // addressed to the group address gaddr on the interface ifi.
   240  // Network must be "udp", "udp4" or "udp6".
   241  // ListenMulticastUDP uses the system-assigned multicast interface
   242  // when ifi is nil, although this is not recommended because the
   243  // assignment depends on platforms and sometimes it might require
   244  // routing configuration.
   245  //
   246  // ListenMulticastUDP is just for convenience of simple, small
   247  // applications. There are golang.org/x/net/ipv4 and
   248  // golang.org/x/net/ipv6 packages for general purpose uses.
   249  func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error) {
   250  	switch network {
   251  	case "udp", "udp4", "udp6":
   252  	default:
   253  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: UnknownNetworkError(network)}
   254  	}
   255  	if gaddr == nil || gaddr.IP == nil {
   256  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: errMissingAddress}
   257  	}
   258  	c, err := listenMulticastUDP(context.Background(), network, ifi, gaddr)
   259  	if err != nil {
   260  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: gaddr.opAddr(), Err: err}
   261  	}
   262  	return c, nil
   263  }