Skip to content

Commit

Permalink
Fix UDP Socket Binding Issue on Linux for IPv4 and IPv6
Browse files Browse the repository at this point in the history
On Linux, when using UDP sockets, both IPv6 and IPv4 addresses are
bound to the same socket by default. This can cause issues when
sending and receiving packets across different address families.
Specifically, if we receive a packet from an IPv4 address,
attempting to send a response using an IPv6 address fails.
  • Loading branch information
jkralik committed Sep 17, 2024
1 parent 99a5d13 commit 4ee730c
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions net/connUDP.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ func (c *ControlMessage) GetIfIndex() int {
return c.IfIndex
}

func (c *ControlMessage) GetDst() net.IP {
if c == nil {
return nil
}
return c.Dst
}

type packetConn interface {
SetWriteDeadline(t time.Time) error
WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error)
Expand Down Expand Up @@ -516,6 +523,13 @@ func (c *UDPConn) writeTo(raddr *net.UDPAddr, cm *ControlMessage, buffer []byte)
// because the connection is already established.
return c.connection.Write(buffer)
}
// On Linux, UDP network binds both IPv6 and IPv4 addresses to the same socket.
// When receiving a packet from an IPv4 address, we cannot send a packet from an IPv6 address.
// Therefore, we wrap the connection using an IPv4 packet connection (packetConn).
if !IsIPv6(raddr.IP) && c.packetConn.IsIPv6() {
pc := packetConnIPv4{packetConn: ipv4.NewPacketConn(c.connection)}
return pc.WriteTo(buffer, cm, raddr)
}
return c.packetConn.WriteTo(buffer, cm, raddr)
}

Expand Down

0 comments on commit 4ee730c

Please sign in to comment.