From 8003bd6a5c012784c0b2a2dad93cbec969fac3b0 Mon Sep 17 00:00:00 2001 From: Noah Gold Date: Tue, 12 Mar 2019 15:35:32 -0700 Subject: Make gonet.PacketConn implement net.Conn. gonet.PacketConn now implements net.Conn, allowing it to be returned from net.Dial.Dialer functions. PiperOrigin-RevId: 238111980 Change-Id: I174884385ff4d9b8e9918fac7bbb5b93ca366ba7 --- pkg/tcpip/adapters/gonet/gonet.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) (limited to 'pkg/tcpip/adapters') diff --git a/pkg/tcpip/adapters/gonet/gonet.go b/pkg/tcpip/adapters/gonet/gonet.go index 560b8ac4b..232d44d24 100644 --- a/pkg/tcpip/adapters/gonet/gonet.go +++ b/pkg/tcpip/adapters/gonet/gonet.go @@ -557,6 +557,21 @@ func (c *PacketConn) newRemoteOpError(op string, remote net.Addr, err error) *ne } } +// RemoteAddr implements net.Conn.RemoteAddr. +func (c *PacketConn) RemoteAddr() net.Addr { + a, err := c.ep.GetRemoteAddress() + if err != nil { + return nil + } + return fullToTCPAddr(a) +} + +// Read implements net.Conn.Read +func (c *PacketConn) Read(b []byte) (int, error) { + bytesRead, _, err := c.ReadFrom(b) + return bytesRead, err +} + // ReadFrom implements net.PacketConn.ReadFrom. func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) { deadline := c.readCancel() @@ -570,6 +585,10 @@ func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return copy(b, read), fullToUDPAddr(addr), nil } +func (c *PacketConn) Write(b []byte) (int, error) { + return c.WriteTo(b, nil) +} + // WriteTo implements net.PacketConn.WriteTo. func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) { deadline := c.writeCancel() @@ -581,13 +600,16 @@ func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) { default: } - ua := addr.(*net.UDPAddr) - fullAddr := tcpip.FullAddress{Addr: tcpip.Address(ua.IP), Port: uint16(ua.Port)} + // If we're being called by Write, there is no addr + wopts := tcpip.WriteOptions{} + if addr != nil { + ua := addr.(*net.UDPAddr) + wopts.To = &tcpip.FullAddress{Addr: tcpip.Address(ua.IP), Port: uint16(ua.Port)} + } v := buffer.NewView(len(b)) copy(v, b) - wopts := tcpip.WriteOptions{To: &fullAddr} n, resCh, err := c.ep.Write(tcpip.SlicePayload(v), wopts) if resCh != nil { select { -- cgit v1.2.3