Skip to content

Commit

Permalink
net: return nil UDPAddr from ReadFromUDP
Browse files Browse the repository at this point in the history
In cases where the socket operation has no underlying address,
golang.org/cl/291509 unintentionally changed ReadFromUDP from return a
nil *UDPAddr to a non-nil (but zero value) *UDPAddr.

This may break callers that assume "no address" is always addr == nil,
so change it back to remain nil.

Fixes golang#46238

Change-Id: I8531e8fa16b853ed7560088eabda0b9e3e53f5be
Reviewed-on: https://go-review.googlesource.com/c/go/+/320909
Trust: Michael Pratt <[email protected]>
Trust: Josh Bleecher Snyder <[email protected]>
Reviewed-by: Filippo Valsorda <[email protected]>
Reviewed-by: Josh Bleecher Snyder <[email protected]>
  • Loading branch information
prattmic committed May 19, 2021
1 parent 15a374d commit 658b5e6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/net/udpsock_posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ func (c *UDPConn) readFrom(b []byte, addr *UDPAddr) (int, *UDPAddr, error) {
*addr = UDPAddr{IP: sa.Addr[0:], Port: sa.Port}
case *syscall.SockaddrInet6:
*addr = UDPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneCache.name(int(sa.ZoneId))}
default:
// No sockaddr, so don't return UDPAddr.
addr = nil
}
return n, addr, err
}
Expand Down
29 changes: 29 additions & 0 deletions src/net/udpsock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
package net

import (
"errors"
"internal/testenv"
"os"
"reflect"
"runtime"
"testing"
Expand Down Expand Up @@ -446,6 +448,33 @@ func TestUDPReadSizeError(t *testing.T) {
}
}

// TestUDPReadTimeout verifies that ReadFromUDP with timeout returns an error
// without data or an address.
func TestUDPReadTimeout(t *testing.T) {
la, err := ResolveUDPAddr("udp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
c, err := ListenUDP("udp4", la)
if err != nil {
t.Fatal(err)
}
defer c.Close()

c.SetDeadline(time.Now())
b := make([]byte, 1)
n, addr, err := c.ReadFromUDP(b)
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Errorf("ReadFromUDP got err %v want os.ErrDeadlineExceeded", err)
}
if n != 0 {
t.Errorf("ReadFromUDP got n %d want 0", n)
}
if addr != nil {
t.Errorf("ReadFromUDP got addr %+#v want nil", addr)
}
}

func BenchmarkWriteToReadFromUDP(b *testing.B) {
conn, err := ListenUDP("udp4", &UDPAddr{IP: IPv4(127, 0, 0, 1)})
if err != nil {
Expand Down

0 comments on commit 658b5e6

Please sign in to comment.