Source file src/net/udpsock_test.go

     1  // Copyright 2012 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  	"errors"
     9  	"fmt"
    10  	"internal/asan"
    11  	"internal/testenv"
    12  	"net/netip"
    13  	"os"
    14  	"reflect"
    15  	"runtime"
    16  	"testing"
    17  	"time"
    18  )
    19  
    20  func BenchmarkUDP6LinkLocalUnicast(b *testing.B) {
    21  	testHookUninstaller.Do(uninstallTestHooks)
    22  
    23  	if !supportsIPv6() {
    24  		b.Skip("IPv6 is not supported")
    25  	}
    26  	ifi := loopbackInterface()
    27  	if ifi == nil {
    28  		b.Skip("loopback interface not found")
    29  	}
    30  	lla := ipv6LinkLocalUnicastAddr(ifi)
    31  	if lla == "" {
    32  		b.Skip("IPv6 link-local unicast address not found")
    33  	}
    34  
    35  	c1, err := ListenPacket("udp6", JoinHostPort(lla+"%"+ifi.Name, "0"))
    36  	if err != nil {
    37  		b.Fatal(err)
    38  	}
    39  	defer c1.Close()
    40  	c2, err := ListenPacket("udp6", JoinHostPort(lla+"%"+ifi.Name, "0"))
    41  	if err != nil {
    42  		b.Fatal(err)
    43  	}
    44  	defer c2.Close()
    45  
    46  	var buf [1]byte
    47  	for i := 0; i < b.N; i++ {
    48  		if _, err := c1.WriteTo(buf[:], c2.LocalAddr()); err != nil {
    49  			b.Fatal(err)
    50  		}
    51  		if _, _, err := c2.ReadFrom(buf[:]); err != nil {
    52  			b.Fatal(err)
    53  		}
    54  	}
    55  }
    56  
    57  type resolveUDPAddrTest struct {
    58  	network       string
    59  	litAddrOrName string
    60  	addr          *UDPAddr
    61  	err           error
    62  }
    63  
    64  var resolveUDPAddrTests = []resolveUDPAddrTest{
    65  	{"udp", "127.0.0.1:0", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 0}, nil},
    66  	{"udp4", "127.0.0.1:65535", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 65535}, nil},
    67  
    68  	{"udp", "[::1]:0", &UDPAddr{IP: ParseIP("::1"), Port: 0}, nil},
    69  	{"udp6", "[::1]:65535", &UDPAddr{IP: ParseIP("::1"), Port: 65535}, nil},
    70  
    71  	{"udp", "[::1%en0]:1", &UDPAddr{IP: ParseIP("::1"), Port: 1, Zone: "en0"}, nil},
    72  	{"udp6", "[::1%911]:2", &UDPAddr{IP: ParseIP("::1"), Port: 2, Zone: "911"}, nil},
    73  
    74  	{"", "127.0.0.1:0", &UDPAddr{IP: IPv4(127, 0, 0, 1), Port: 0}, nil}, // Go 1.0 behavior
    75  	{"", "[::1]:0", &UDPAddr{IP: ParseIP("::1"), Port: 0}, nil},         // Go 1.0 behavior
    76  
    77  	{"udp", ":12345", &UDPAddr{Port: 12345}, nil},
    78  
    79  	{"http", "127.0.0.1:0", nil, UnknownNetworkError("http")},
    80  
    81  	{"udp", "127.0.0.1:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
    82  	{"udp", "[::ffff:127.0.0.1]:domain", &UDPAddr{IP: ParseIP("::ffff:127.0.0.1"), Port: 53}, nil},
    83  	{"udp", "[2001:db8::1]:domain", &UDPAddr{IP: ParseIP("2001:db8::1"), Port: 53}, nil},
    84  	{"udp4", "127.0.0.1:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
    85  	{"udp4", "[::ffff:127.0.0.1]:domain", &UDPAddr{IP: ParseIP("127.0.0.1"), Port: 53}, nil},
    86  	{"udp6", "[2001:db8::1]:domain", &UDPAddr{IP: ParseIP("2001:db8::1"), Port: 53}, nil},
    87  
    88  	{"udp4", "[2001:db8::1]:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "2001:db8::1"}},
    89  	{"udp6", "127.0.0.1:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "127.0.0.1"}},
    90  	{"udp6", "[::ffff:127.0.0.1]:domain", nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: "::ffff:127.0.0.1"}},
    91  }
    92  
    93  func TestResolveUDPAddr(t *testing.T) {
    94  	origTestHookLookupIP := testHookLookupIP
    95  	defer func() { testHookLookupIP = origTestHookLookupIP }()
    96  	testHookLookupIP = lookupLocalhost
    97  
    98  	for _, tt := range resolveUDPAddrTests {
    99  		addr, err := ResolveUDPAddr(tt.network, tt.litAddrOrName)
   100  		if !reflect.DeepEqual(addr, tt.addr) || !reflect.DeepEqual(err, tt.err) {
   101  			t.Errorf("ResolveUDPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr, err, tt.addr, tt.err)
   102  			continue
   103  		}
   104  		if err == nil {
   105  			addr2, err := ResolveUDPAddr(addr.Network(), addr.String())
   106  			if !reflect.DeepEqual(addr2, tt.addr) || err != tt.err {
   107  				t.Errorf("(%q, %q): ResolveUDPAddr(%q, %q) = %#v, %v, want %#v, %v", tt.network, tt.litAddrOrName, addr.Network(), addr.String(), addr2, err, tt.addr, tt.err)
   108  			}
   109  		}
   110  	}
   111  }
   112  
   113  func TestWriteToUDP(t *testing.T) {
   114  	switch runtime.GOOS {
   115  	case "plan9":
   116  		t.Skipf("not supported on %s", runtime.GOOS)
   117  	}
   118  
   119  	if !testableNetwork("udp") {
   120  		t.Skipf("skipping: udp not supported")
   121  	}
   122  
   123  	c, err := ListenPacket("udp", "127.0.0.1:0")
   124  	if err != nil {
   125  		t.Fatal(err)
   126  	}
   127  	defer c.Close()
   128  
   129  	testWriteToConn(t, c.LocalAddr().String())
   130  	testWriteToPacketConn(t, c.LocalAddr().String())
   131  }
   132  
   133  func testWriteToConn(t *testing.T, raddr string) {
   134  	c, err := Dial("udp", raddr)
   135  	if err != nil {
   136  		t.Fatal(err)
   137  	}
   138  	defer c.Close()
   139  
   140  	ra, err := ResolveUDPAddr("udp", raddr)
   141  	if err != nil {
   142  		t.Fatal(err)
   143  	}
   144  
   145  	b := []byte("CONNECTED-MODE SOCKET")
   146  	_, err = c.(*UDPConn).WriteToUDP(b, ra)
   147  	if err == nil {
   148  		t.Fatal("should fail")
   149  	}
   150  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
   151  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
   152  	}
   153  	_, err = c.(*UDPConn).WriteTo(b, ra)
   154  	if err == nil {
   155  		t.Fatal("should fail")
   156  	}
   157  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
   158  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
   159  	}
   160  	_, err = c.Write(b)
   161  	if err != nil {
   162  		t.Fatal(err)
   163  	}
   164  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, ra)
   165  	if err == nil {
   166  		t.Fatal("should fail")
   167  	}
   168  	if err != nil && err.(*OpError).Err != ErrWriteToConnected {
   169  		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
   170  	}
   171  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, nil)
   172  	if err != nil {
   173  		t.Fatal(err)
   174  	}
   175  }
   176  
   177  func testWriteToPacketConn(t *testing.T, raddr string) {
   178  	c, err := ListenPacket("udp", "127.0.0.1:0")
   179  	if err != nil {
   180  		t.Fatal(err)
   181  	}
   182  	defer c.Close()
   183  
   184  	ra, err := ResolveUDPAddr("udp", raddr)
   185  	if err != nil {
   186  		t.Fatal(err)
   187  	}
   188  
   189  	b := []byte("UNCONNECTED-MODE SOCKET")
   190  	_, err = c.(*UDPConn).WriteToUDP(b, ra)
   191  	if err != nil {
   192  		t.Fatal(err)
   193  	}
   194  	_, err = c.WriteTo(b, ra)
   195  	if err != nil {
   196  		t.Fatal(err)
   197  	}
   198  	_, err = c.(*UDPConn).Write(b)
   199  	if err == nil {
   200  		t.Fatal("should fail")
   201  	}
   202  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, nil)
   203  	if err == nil {
   204  		t.Fatal("should fail")
   205  	}
   206  	if err != nil && err.(*OpError).Err != errMissingAddress {
   207  		t.Fatalf("should fail as errMissingAddress: %v", err)
   208  	}
   209  	_, _, err = c.(*UDPConn).WriteMsgUDP(b, nil, ra)
   210  	if err != nil {
   211  		t.Fatal(err)
   212  	}
   213  }
   214  
   215  var udpConnLocalNameTests = []struct {
   216  	net   string
   217  	laddr *UDPAddr
   218  }{
   219  	{"udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)}},
   220  	{"udp4", &UDPAddr{}},
   221  	{"udp4", nil},
   222  }
   223  
   224  func TestUDPConnLocalName(t *testing.T) {
   225  	testenv.MustHaveExternalNetwork(t)
   226  
   227  	for _, tt := range udpConnLocalNameTests {
   228  		t.Run(fmt.Sprint(tt.laddr), func(t *testing.T) {
   229  			if !testableNetwork(tt.net) {
   230  				t.Skipf("skipping: %s not available", tt.net)
   231  			}
   232  
   233  			c, err := ListenUDP(tt.net, tt.laddr)
   234  			if err != nil {
   235  				t.Fatal(err)
   236  			}
   237  			defer c.Close()
   238  			la := c.LocalAddr()
   239  			if a, ok := la.(*UDPAddr); !ok || a.Port == 0 {
   240  				t.Fatalf("got %v; expected a proper address with non-zero port number", la)
   241  			}
   242  		})
   243  	}
   244  }
   245  
   246  func TestUDPConnLocalAndRemoteNames(t *testing.T) {
   247  	if !testableNetwork("udp") {
   248  		t.Skipf("skipping: udp not available")
   249  	}
   250  
   251  	for _, laddr := range []string{"", "127.0.0.1:0"} {
   252  		c1, err := ListenPacket("udp", "127.0.0.1:0")
   253  		if err != nil {
   254  			t.Fatal(err)
   255  		}
   256  		defer c1.Close()
   257  
   258  		var la *UDPAddr
   259  		if laddr != "" {
   260  			var err error
   261  			if la, err = ResolveUDPAddr("udp", laddr); err != nil {
   262  				t.Fatal(err)
   263  			}
   264  		}
   265  		c2, err := DialUDP("udp", la, c1.LocalAddr().(*UDPAddr))
   266  		if err != nil {
   267  			t.Fatal(err)
   268  		}
   269  		defer c2.Close()
   270  
   271  		var connAddrs = [4]struct {
   272  			got Addr
   273  			ok  bool
   274  		}{
   275  			{c1.LocalAddr(), true},
   276  			{c1.(*UDPConn).RemoteAddr(), false},
   277  			{c2.LocalAddr(), true},
   278  			{c2.RemoteAddr(), true},
   279  		}
   280  		for _, ca := range connAddrs {
   281  			if a, ok := ca.got.(*UDPAddr); ok != ca.ok || ok && a.Port == 0 {
   282  				t.Fatalf("got %v; expected a proper address with non-zero port number", ca.got)
   283  			}
   284  		}
   285  	}
   286  }
   287  
   288  func TestIPv6LinkLocalUnicastUDP(t *testing.T) {
   289  	testenv.MustHaveExternalNetwork(t)
   290  
   291  	if !supportsIPv6() {
   292  		t.Skip("IPv6 is not supported")
   293  	}
   294  
   295  	for i, tt := range ipv6LinkLocalUnicastUDPTests {
   296  		c1, err := ListenPacket(tt.network, tt.address)
   297  		if err != nil {
   298  			// It might return "LookupHost returned no
   299  			// suitable address" error on some platforms.
   300  			t.Log(err)
   301  			continue
   302  		}
   303  		ls := (&packetListener{PacketConn: c1}).newLocalServer()
   304  		defer ls.teardown()
   305  		ch := make(chan error, 1)
   306  		handler := func(ls *localPacketServer, c PacketConn) { packetTransponder(c, ch) }
   307  		if err := ls.buildup(handler); err != nil {
   308  			t.Fatal(err)
   309  		}
   310  		if la, ok := c1.LocalAddr().(*UDPAddr); !ok || !tt.nameLookup && la.Zone == "" {
   311  			t.Fatalf("got %v; expected a proper address with zone identifier", la)
   312  		}
   313  
   314  		c2, err := Dial(tt.network, ls.PacketConn.LocalAddr().String())
   315  		if err != nil {
   316  			t.Fatal(err)
   317  		}
   318  		defer c2.Close()
   319  		if la, ok := c2.LocalAddr().(*UDPAddr); !ok || !tt.nameLookup && la.Zone == "" {
   320  			t.Fatalf("got %v; expected a proper address with zone identifier", la)
   321  		}
   322  		if ra, ok := c2.RemoteAddr().(*UDPAddr); !ok || !tt.nameLookup && ra.Zone == "" {
   323  			t.Fatalf("got %v; expected a proper address with zone identifier", ra)
   324  		}
   325  
   326  		if _, err := c2.Write([]byte("UDP OVER IPV6 LINKLOCAL TEST")); err != nil {
   327  			t.Fatal(err)
   328  		}
   329  		b := make([]byte, 32)
   330  		if _, err := c2.Read(b); err != nil {
   331  			t.Fatal(err)
   332  		}
   333  
   334  		for err := range ch {
   335  			t.Errorf("#%d: %v", i, err)
   336  		}
   337  	}
   338  }
   339  
   340  func TestUDPZeroBytePayload(t *testing.T) {
   341  	switch runtime.GOOS {
   342  	case "plan9":
   343  		t.Skipf("not supported on %s", runtime.GOOS)
   344  	case "ios":
   345  		testenv.SkipFlaky(t, 29225)
   346  	}
   347  	if !testableNetwork("udp") {
   348  		t.Skipf("skipping: udp not available")
   349  	}
   350  
   351  	c := newLocalPacketListener(t, "udp")
   352  	defer c.Close()
   353  
   354  	for _, genericRead := range []bool{false, true} {
   355  		n, err := c.WriteTo(nil, c.LocalAddr())
   356  		if err != nil {
   357  			t.Fatal(err)
   358  		}
   359  		if n != 0 {
   360  			t.Errorf("got %d; want 0", n)
   361  		}
   362  		c.SetReadDeadline(time.Now().Add(30 * time.Second))
   363  		var b [1]byte
   364  		var name string
   365  		if genericRead {
   366  			_, err = c.(Conn).Read(b[:])
   367  			name = "Read"
   368  		} else {
   369  			_, _, err = c.ReadFrom(b[:])
   370  			name = "ReadFrom"
   371  		}
   372  		if err != nil {
   373  			t.Errorf("%s of zero byte packet failed: %v", name, err)
   374  		}
   375  	}
   376  }
   377  
   378  func TestUDPZeroByteBuffer(t *testing.T) {
   379  	switch runtime.GOOS {
   380  	case "plan9":
   381  		t.Skipf("not supported on %s", runtime.GOOS)
   382  	}
   383  	if !testableNetwork("udp") {
   384  		t.Skipf("skipping: udp not available")
   385  	}
   386  
   387  	c := newLocalPacketListener(t, "udp")
   388  	defer c.Close()
   389  
   390  	b := []byte("UDP ZERO BYTE BUFFER TEST")
   391  	for _, genericRead := range []bool{false, true} {
   392  		n, err := c.WriteTo(b, c.LocalAddr())
   393  		if err != nil {
   394  			t.Fatal(err)
   395  		}
   396  		if n != len(b) {
   397  			t.Errorf("got %d; want %d", n, len(b))
   398  		}
   399  		c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
   400  		if genericRead {
   401  			_, err = c.(Conn).Read(nil)
   402  		} else {
   403  			_, _, err = c.ReadFrom(nil)
   404  		}
   405  		switch err {
   406  		case nil: // ReadFrom succeeds
   407  		default: // Read may timeout, it depends on the platform
   408  			if nerr, ok := err.(Error); (!ok || !nerr.Timeout()) && runtime.GOOS != "windows" { // Windows returns WSAEMSGSIZE
   409  				t.Fatal(err)
   410  			}
   411  		}
   412  	}
   413  }
   414  
   415  func TestUDPReadSizeError(t *testing.T) {
   416  	switch runtime.GOOS {
   417  	case "plan9":
   418  		t.Skipf("not supported on %s", runtime.GOOS)
   419  	}
   420  	if !testableNetwork("udp") {
   421  		t.Skipf("skipping: udp not available")
   422  	}
   423  
   424  	c1 := newLocalPacketListener(t, "udp")
   425  	defer c1.Close()
   426  
   427  	c2, err := Dial("udp", c1.LocalAddr().String())
   428  	if err != nil {
   429  		t.Fatal(err)
   430  	}
   431  	defer c2.Close()
   432  
   433  	b1 := []byte("READ SIZE ERROR TEST")
   434  	for _, genericRead := range []bool{false, true} {
   435  		n, err := c2.Write(b1)
   436  		if err != nil {
   437  			t.Fatal(err)
   438  		}
   439  		if n != len(b1) {
   440  			t.Errorf("got %d; want %d", n, len(b1))
   441  		}
   442  		b2 := make([]byte, len(b1)-1)
   443  		if genericRead {
   444  			n, err = c1.(Conn).Read(b2)
   445  		} else {
   446  			n, _, err = c1.ReadFrom(b2)
   447  		}
   448  		if err != nil && runtime.GOOS != "windows" { // Windows returns WSAEMSGSIZE
   449  			t.Fatal(err)
   450  		}
   451  		if n != len(b1)-1 {
   452  			t.Fatalf("got %d; want %d", n, len(b1)-1)
   453  		}
   454  	}
   455  }
   456  
   457  // TestUDPReadTimeout verifies that ReadFromUDP with timeout returns an error
   458  // without data or an address.
   459  func TestUDPReadTimeout(t *testing.T) {
   460  	if !testableNetwork("udp4") {
   461  		t.Skipf("skipping: udp4 not available")
   462  	}
   463  
   464  	la, err := ResolveUDPAddr("udp4", "127.0.0.1:0")
   465  	if err != nil {
   466  		t.Fatal(err)
   467  	}
   468  	c, err := ListenUDP("udp4", la)
   469  	if err != nil {
   470  		t.Fatal(err)
   471  	}
   472  	defer c.Close()
   473  
   474  	c.SetDeadline(time.Now())
   475  	b := make([]byte, 1)
   476  	n, addr, err := c.ReadFromUDP(b)
   477  	if !errors.Is(err, os.ErrDeadlineExceeded) {
   478  		t.Errorf("ReadFromUDP got err %v want os.ErrDeadlineExceeded", err)
   479  	}
   480  	if n != 0 {
   481  		t.Errorf("ReadFromUDP got n %d want 0", n)
   482  	}
   483  	if addr != nil {
   484  		t.Errorf("ReadFromUDP got addr %+#v want nil", addr)
   485  	}
   486  }
   487  
   488  func TestAllocs(t *testing.T) {
   489  	switch runtime.GOOS {
   490  	case "plan9", "js", "wasip1":
   491  		// These implementations have not been optimized.
   492  		t.Skipf("skipping on %v", runtime.GOOS)
   493  	}
   494  	if !testableNetwork("udp4") {
   495  		t.Skipf("skipping: udp4 not available")
   496  	}
   497  	if asan.Enabled {
   498  		t.Skip("test allocates more with -asan; see #70079")
   499  	}
   500  
   501  	// Optimizations are required to remove the allocs.
   502  	testenv.SkipIfOptimizationOff(t)
   503  
   504  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
   505  	if err != nil {
   506  		t.Fatal(err)
   507  	}
   508  	defer conn.Close()
   509  	addr := conn.LocalAddr()
   510  	addrPort := addr.(*UDPAddr).AddrPort()
   511  	buf := make([]byte, 8)
   512  
   513  	allocs := testing.AllocsPerRun(1000, func() {
   514  		_, _, err := conn.WriteMsgUDPAddrPort(buf, nil, addrPort)
   515  		if err != nil {
   516  			t.Fatal(err)
   517  		}
   518  		_, _, _, _, err = conn.ReadMsgUDPAddrPort(buf, nil)
   519  		if err != nil {
   520  			t.Fatal(err)
   521  		}
   522  	})
   523  	if got := int(allocs); got != 0 {
   524  		t.Errorf("WriteMsgUDPAddrPort/ReadMsgUDPAddrPort allocated %d objects", got)
   525  	}
   526  
   527  	allocs = testing.AllocsPerRun(1000, func() {
   528  		_, err := conn.WriteToUDPAddrPort(buf, addrPort)
   529  		if err != nil {
   530  			t.Fatal(err)
   531  		}
   532  		_, _, err = conn.ReadFromUDPAddrPort(buf)
   533  		if err != nil {
   534  			t.Fatal(err)
   535  		}
   536  	})
   537  	if got := int(allocs); got != 0 {
   538  		t.Errorf("WriteToUDPAddrPort/ReadFromUDPAddrPort allocated %d objects", got)
   539  	}
   540  
   541  	allocs = testing.AllocsPerRun(1000, func() {
   542  		_, err := conn.WriteTo(buf, addr)
   543  		if err != nil {
   544  			t.Fatal(err)
   545  		}
   546  		_, _, err = conn.ReadFromUDP(buf)
   547  		if err != nil {
   548  			t.Fatal(err)
   549  		}
   550  	})
   551  	if got := int(allocs); got != 1 {
   552  		t.Errorf("WriteTo/ReadFromUDP allocated %d objects", got)
   553  	}
   554  }
   555  
   556  func BenchmarkReadWriteMsgUDPAddrPort(b *testing.B) {
   557  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
   558  	if err != nil {
   559  		b.Fatal(err)
   560  	}
   561  	defer conn.Close()
   562  	addr := conn.LocalAddr().(*UDPAddr).AddrPort()
   563  	buf := make([]byte, 8)
   564  	b.ResetTimer()
   565  	b.ReportAllocs()
   566  	for i := 0; i < b.N; i++ {
   567  		_, _, err := conn.WriteMsgUDPAddrPort(buf, nil, addr)
   568  		if err != nil {
   569  			b.Fatal(err)
   570  		}
   571  		_, _, _, _, err = conn.ReadMsgUDPAddrPort(buf, nil)
   572  		if err != nil {
   573  			b.Fatal(err)
   574  		}
   575  	}
   576  }
   577  
   578  func BenchmarkWriteToReadFromUDP(b *testing.B) {
   579  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
   580  	if err != nil {
   581  		b.Fatal(err)
   582  	}
   583  	defer conn.Close()
   584  	addr := conn.LocalAddr()
   585  	buf := make([]byte, 8)
   586  	b.ResetTimer()
   587  	b.ReportAllocs()
   588  	for i := 0; i < b.N; i++ {
   589  		_, err := conn.WriteTo(buf, addr)
   590  		if err != nil {
   591  			b.Fatal(err)
   592  		}
   593  		_, _, err = conn.ReadFromUDP(buf)
   594  		if err != nil {
   595  			b.Fatal(err)
   596  		}
   597  	}
   598  }
   599  
   600  func BenchmarkWriteToReadFromUDPAddrPort(b *testing.B) {
   601  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
   602  	if err != nil {
   603  		b.Fatal(err)
   604  	}
   605  	defer conn.Close()
   606  	addr := conn.LocalAddr().(*UDPAddr).AddrPort()
   607  	buf := make([]byte, 8)
   608  	b.ResetTimer()
   609  	b.ReportAllocs()
   610  	for i := 0; i < b.N; i++ {
   611  		_, err := conn.WriteToUDPAddrPort(buf, addr)
   612  		if err != nil {
   613  			b.Fatal(err)
   614  		}
   615  		_, _, err = conn.ReadFromUDPAddrPort(buf)
   616  		if err != nil {
   617  			b.Fatal(err)
   618  		}
   619  	}
   620  }
   621  
   622  func TestUDPIPVersionReadMsg(t *testing.T) {
   623  	switch runtime.GOOS {
   624  	case "plan9":
   625  		t.Skipf("skipping on %v", runtime.GOOS)
   626  	}
   627  	if !testableNetwork("udp4") {
   628  		t.Skipf("skipping: udp4 not available")
   629  	}
   630  
   631  	conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
   632  	if err != nil {
   633  		t.Fatal(err)
   634  	}
   635  	defer conn.Close()
   636  	daddr := conn.LocalAddr().(*UDPAddr).AddrPort()
   637  	buf := make([]byte, 8)
   638  	_, err = conn.WriteToUDPAddrPort(buf, daddr)
   639  	if err != nil {
   640  		t.Fatal(err)
   641  	}
   642  	_, _, _, saddr, err := conn.ReadMsgUDPAddrPort(buf, nil)
   643  	if err != nil {
   644  		t.Fatal(err)
   645  	}
   646  	if !saddr.Addr().Is4() {
   647  		t.Error("returned AddrPort is not IPv4")
   648  	}
   649  	_, err = conn.WriteToUDPAddrPort(buf, daddr)
   650  	if err != nil {
   651  		t.Fatal(err)
   652  	}
   653  	_, _, _, soldaddr, err := conn.ReadMsgUDP(buf, nil)
   654  	if err != nil {
   655  		t.Fatal(err)
   656  	}
   657  	if len(soldaddr.IP) != 4 {
   658  		t.Error("returned UDPAddr is not IPv4")
   659  	}
   660  }
   661  
   662  // TestIPv6WriteMsgUDPAddrPortTargetAddrIPVersion verifies that
   663  // WriteMsgUDPAddrPort accepts IPv4, IPv4-mapped IPv6, and IPv6 target addresses
   664  // on a UDPConn listening on "::".
   665  func TestIPv6WriteMsgUDPAddrPortTargetAddrIPVersion(t *testing.T) {
   666  	if !testableNetwork("udp4") {
   667  		t.Skipf("skipping: udp4 not available")
   668  	}
   669  	if !testableNetwork("udp6") {
   670  		t.Skipf("skipping: udp6 not available")
   671  	}
   672  
   673  	switch runtime.GOOS {
   674  	case "dragonfly", "openbsd":
   675  		// DragonflyBSD's IPv6 sockets are always IPv6-only, according to the man page:
   676  		// https://www.dragonflybsd.org/cgi/web-man?command=ip6 (search for IPV6_V6ONLY).
   677  		// OpenBSD's IPv6 sockets are always IPv6-only, according to the man page:
   678  		// https://man.openbsd.org/ip6#IPV6_V6ONLY
   679  		t.Skipf("skipping on %v", runtime.GOOS)
   680  	}
   681  
   682  	conn, err := ListenUDP("udp", nil)
   683  	if err != nil {
   684  		t.Fatal(err)
   685  	}
   686  	defer conn.Close()
   687  
   688  	daddr4 := netip.AddrPortFrom(netip.MustParseAddr("127.0.0.1"), 12345)
   689  	daddr4in6 := netip.AddrPortFrom(netip.MustParseAddr("::ffff:127.0.0.1"), 12345)
   690  	daddr6 := netip.AddrPortFrom(netip.MustParseAddr("::1"), 12345)
   691  	buf := make([]byte, 8)
   692  
   693  	_, _, err = conn.WriteMsgUDPAddrPort(buf, nil, daddr4)
   694  	if err != nil {
   695  		t.Fatal(err)
   696  	}
   697  
   698  	_, _, err = conn.WriteMsgUDPAddrPort(buf, nil, daddr4in6)
   699  	if err != nil {
   700  		t.Fatal(err)
   701  	}
   702  
   703  	_, _, err = conn.WriteMsgUDPAddrPort(buf, nil, daddr6)
   704  	if err != nil {
   705  		t.Fatal(err)
   706  	}
   707  }
   708  

View as plain text