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 5da2f7d
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions net/connUDP.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,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 5da2f7d

Please sign in to comment.