github.com/roboticscm/goman@v0.0.0-20210203095141-87c07b4a0a55/src/net/udpsock_posix.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  // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows
     6  
     7  package net
     8  
     9  import (
    10  	"syscall"
    11  	"time"
    12  )
    13  
    14  func sockaddrToUDP(sa syscall.Sockaddr) Addr {
    15  	switch sa := sa.(type) {
    16  	case *syscall.SockaddrInet4:
    17  		return &UDPAddr{IP: sa.Addr[0:], Port: sa.Port}
    18  	case *syscall.SockaddrInet6:
    19  		return &UDPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneToString(int(sa.ZoneId))}
    20  	}
    21  	return nil
    22  }
    23  
    24  func (a *UDPAddr) family() int {
    25  	if a == nil || len(a.IP) <= IPv4len {
    26  		return syscall.AF_INET
    27  	}
    28  	if a.IP.To4() != nil {
    29  		return syscall.AF_INET
    30  	}
    31  	return syscall.AF_INET6
    32  }
    33  
    34  func (a *UDPAddr) isWildcard() bool {
    35  	if a == nil || a.IP == nil {
    36  		return true
    37  	}
    38  	return a.IP.IsUnspecified()
    39  }
    40  
    41  func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
    42  	if a == nil {
    43  		return nil, nil
    44  	}
    45  	return ipToSockaddr(family, a.IP, a.Port, a.Zone)
    46  }
    47  
    48  // UDPConn is the implementation of the Conn and PacketConn interfaces
    49  // for UDP network connections.
    50  type UDPConn struct {
    51  	conn
    52  }
    53  
    54  func newUDPConn(fd *netFD) *UDPConn { return &UDPConn{conn{fd}} }
    55  
    56  // ReadFromUDP reads a UDP packet from c, copying the payload into b.
    57  // It returns the number of bytes copied into b and the return address
    58  // that was on the packet.
    59  //
    60  // ReadFromUDP can be made to time out and return an error with
    61  // Timeout() == true after a fixed time limit; see SetDeadline and
    62  // SetReadDeadline.
    63  func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) {
    64  	if !c.ok() {
    65  		return 0, nil, syscall.EINVAL
    66  	}
    67  	n, sa, err := c.fd.readFrom(b)
    68  	switch sa := sa.(type) {
    69  	case *syscall.SockaddrInet4:
    70  		addr = &UDPAddr{IP: sa.Addr[0:], Port: sa.Port}
    71  	case *syscall.SockaddrInet6:
    72  		addr = &UDPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneToString(int(sa.ZoneId))}
    73  	}
    74  	return
    75  }
    76  
    77  // ReadFrom implements the PacketConn ReadFrom method.
    78  func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error) {
    79  	if !c.ok() {
    80  		return 0, nil, syscall.EINVAL
    81  	}
    82  	n, addr, err := c.ReadFromUDP(b)
    83  	return n, addr.toAddr(), err
    84  }
    85  
    86  // ReadMsgUDP reads a packet from c, copying the payload into b and
    87  // the associated out-of-band data into oob.  It returns the number
    88  // of bytes copied into b, the number of bytes copied into oob, the
    89  // flags that were set on the packet and the source address of the
    90  // packet.
    91  func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error) {
    92  	if !c.ok() {
    93  		return 0, 0, 0, nil, syscall.EINVAL
    94  	}
    95  	var sa syscall.Sockaddr
    96  	n, oobn, flags, sa, err = c.fd.readMsg(b, oob)
    97  	switch sa := sa.(type) {
    98  	case *syscall.SockaddrInet4:
    99  		addr = &UDPAddr{IP: sa.Addr[0:], Port: sa.Port}
   100  	case *syscall.SockaddrInet6:
   101  		addr = &UDPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneToString(int(sa.ZoneId))}
   102  	}
   103  	return
   104  }
   105  
   106  // WriteToUDP writes a UDP packet to addr via c, copying the payload
   107  // from b.
   108  //
   109  // WriteToUDP can be made to time out and return an error with
   110  // Timeout() == true after a fixed time limit; see SetDeadline and
   111  // SetWriteDeadline.  On packet-oriented connections, write timeouts
   112  // are rare.
   113  func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error) {
   114  	if !c.ok() {
   115  		return 0, syscall.EINVAL
   116  	}
   117  	if c.fd.isConnected {
   118  		return 0, &OpError{"write", c.fd.net, addr, ErrWriteToConnected}
   119  	}
   120  	if addr == nil {
   121  		return 0, &OpError{Op: "write", Net: c.fd.net, Addr: nil, Err: errMissingAddress}
   122  	}
   123  	sa, err := addr.sockaddr(c.fd.family)
   124  	if err != nil {
   125  		return 0, &OpError{"write", c.fd.net, addr, err}
   126  	}
   127  	return c.fd.writeTo(b, sa)
   128  }
   129  
   130  // WriteTo implements the PacketConn WriteTo method.
   131  func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error) {
   132  	if !c.ok() {
   133  		return 0, syscall.EINVAL
   134  	}
   135  	a, ok := addr.(*UDPAddr)
   136  	if !ok {
   137  		return 0, &OpError{"write", c.fd.net, addr, syscall.EINVAL}
   138  	}
   139  	return c.WriteToUDP(b, a)
   140  }
   141  
   142  // WriteMsgUDP writes a packet to addr via c, copying the payload from
   143  // b and the associated out-of-band data from oob.  It returns the
   144  // number of payload and out-of-band bytes written.
   145  func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error) {
   146  	if !c.ok() {
   147  		return 0, 0, syscall.EINVAL
   148  	}
   149  	if c.fd.isConnected {
   150  		return 0, 0, &OpError{"write", c.fd.net, addr, ErrWriteToConnected}
   151  	}
   152  	if addr == nil {
   153  		return 0, 0, &OpError{Op: "write", Net: c.fd.net, Addr: nil, Err: errMissingAddress}
   154  	}
   155  	sa, err := addr.sockaddr(c.fd.family)
   156  	if err != nil {
   157  		return 0, 0, &OpError{"write", c.fd.net, addr, err}
   158  	}
   159  	return c.fd.writeMsg(b, oob, sa)
   160  }
   161  
   162  // DialUDP connects to the remote address raddr on the network net,
   163  // which must be "udp", "udp4", or "udp6".  If laddr is not nil, it is
   164  // used as the local address for the connection.
   165  func DialUDP(net string, laddr, raddr *UDPAddr) (*UDPConn, error) {
   166  	switch net {
   167  	case "udp", "udp4", "udp6":
   168  	default:
   169  		return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: UnknownNetworkError(net)}
   170  	}
   171  	if raddr == nil {
   172  		return nil, &OpError{Op: "dial", Net: net, Addr: nil, Err: errMissingAddress}
   173  	}
   174  	return dialUDP(net, laddr, raddr, noDeadline)
   175  }
   176  
   177  func dialUDP(net string, laddr, raddr *UDPAddr, deadline time.Time) (*UDPConn, error) {
   178  	fd, err := internetSocket(net, laddr, raddr, deadline, syscall.SOCK_DGRAM, 0, "dial")
   179  	if err != nil {
   180  		return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: err}
   181  	}
   182  	return newUDPConn(fd), nil
   183  }
   184  
   185  // ListenUDP listens for incoming UDP packets addressed to the local
   186  // address laddr.  Net must be "udp", "udp4", or "udp6".  If laddr has
   187  // a port of 0, ListenUDP will choose an available port.
   188  // The LocalAddr method of the returned UDPConn can be used to
   189  // discover the port.  The returned connection's ReadFrom and WriteTo
   190  // methods can be used to receive and send UDP packets with per-packet
   191  // addressing.
   192  func ListenUDP(net string, laddr *UDPAddr) (*UDPConn, error) {
   193  	switch net {
   194  	case "udp", "udp4", "udp6":
   195  	default:
   196  		return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: UnknownNetworkError(net)}
   197  	}
   198  	if laddr == nil {
   199  		laddr = &UDPAddr{}
   200  	}
   201  	fd, err := internetSocket(net, laddr, nil, noDeadline, syscall.SOCK_DGRAM, 0, "listen")
   202  	if err != nil {
   203  		return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: err}
   204  	}
   205  	return newUDPConn(fd), nil
   206  }
   207  
   208  // ListenMulticastUDP listens for incoming multicast UDP packets
   209  // addressed to the group address gaddr on ifi, which specifies the
   210  // interface to join.  ListenMulticastUDP uses default multicast
   211  // interface if ifi is nil.
   212  func ListenMulticastUDP(net string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error) {
   213  	switch net {
   214  	case "udp", "udp4", "udp6":
   215  	default:
   216  		return nil, &OpError{Op: "listen", Net: net, Addr: gaddr, Err: UnknownNetworkError(net)}
   217  	}
   218  	if gaddr == nil || gaddr.IP == nil {
   219  		return nil, &OpError{Op: "listen", Net: net, Addr: nil, Err: errMissingAddress}
   220  	}
   221  	fd, err := internetSocket(net, gaddr, nil, noDeadline, syscall.SOCK_DGRAM, 0, "listen")
   222  	if err != nil {
   223  		return nil, &OpError{Op: "listen", Net: net, Addr: gaddr, Err: err}
   224  	}
   225  	c := newUDPConn(fd)
   226  	if ip4 := gaddr.IP.To4(); ip4 != nil {
   227  		if err := listenIPv4MulticastUDP(c, ifi, ip4); err != nil {
   228  			c.Close()
   229  			return nil, &OpError{Op: "listen", Net: net, Addr: &IPAddr{IP: ip4}, Err: err}
   230  		}
   231  	} else {
   232  		if err := listenIPv6MulticastUDP(c, ifi, gaddr.IP); err != nil {
   233  			c.Close()
   234  			return nil, &OpError{Op: "listen", Net: net, Addr: &IPAddr{IP: gaddr.IP}, Err: err}
   235  		}
   236  	}
   237  	return c, nil
   238  }
   239  
   240  func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error {
   241  	if ifi != nil {
   242  		if err := setIPv4MulticastInterface(c.fd, ifi); err != nil {
   243  			return err
   244  		}
   245  	}
   246  	if err := setIPv4MulticastLoopback(c.fd, false); err != nil {
   247  		return err
   248  	}
   249  	if err := joinIPv4Group(c.fd, ifi, ip); err != nil {
   250  		return err
   251  	}
   252  	return nil
   253  }
   254  
   255  func listenIPv6MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error {
   256  	if ifi != nil {
   257  		if err := setIPv6MulticastInterface(c.fd, ifi); err != nil {
   258  			return err
   259  		}
   260  	}
   261  	if err := setIPv6MulticastLoopback(c.fd, false); err != nil {
   262  		return err
   263  	}
   264  	if err := joinIPv6Group(c.fd, ifi, ip); err != nil {
   265  		return err
   266  	}
   267  	return nil
   268  }