Skip to content

Commit 555ec48

Browse files
authored
Fix sending to IPv4 addresses from an IPv6 dual-stack socket (#640) (#641)
* Fix sending to IPv4 addresses from an IPv6 dual-stack socket (#640)
1 parent 97a7523 commit 555ec48

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

net/connUDP.go

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -516,14 +516,25 @@ func (c *UDPConn) writeTo(raddr *net.UDPAddr, cm *ControlMessage, buffer []byte)
516516
// because the connection is already established.
517517
return c.connection.Write(buffer)
518518
}
519-
// On Linux, UDP network binds both IPv6 and IPv4 addresses to the same socket.
520-
// When receiving a packet from an IPv4 address, we cannot send a packet from an IPv6 address.
521-
// Therefore, we wrap the connection using an IPv4 packet connection (packetConn).
522-
if !IsIPv6(raddr.IP) && c.packetConn.IsIPv6() {
523-
pc := packetConnIPv4{packetConn: ipv4.NewPacketConn(c.connection)}
524-
return pc.WriteTo(buffer, cm, raddr)
525-
}
526-
return c.packetConn.WriteTo(buffer, cm, raddr)
519+
520+
var cmb []byte
521+
522+
if cm != nil && IsIPv6(raddr.IP) {
523+
m := &ipv6.ControlMessage{
524+
Src: cm.Src,
525+
IfIndex: cm.IfIndex,
526+
}
527+
cmb = m.Marshal()
528+
} else if cm != nil {
529+
m := &ipv4.ControlMessage{
530+
Src: cm.Src,
531+
IfIndex: cm.IfIndex,
532+
}
533+
cmb = m.Marshal()
534+
}
535+
536+
i, _, err := c.connection.WriteMsgUDP(buffer, cmb, raddr)
537+
return i, err
527538
}
528539

529540
type UDPWriteCfg struct {

net/connUDP_internal_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ func TestUDPConnWriteWithContext(t *testing.T) {
5858
},
5959
wantErr: true,
6060
},
61+
{
62+
name: "send to v4 from v6 socket",
63+
args: args{
64+
ctx: context.Background(),
65+
listenNetwork: udpNetwork,
66+
udpAddr: b,
67+
buffer: []byte("hello world"),
68+
},
69+
wantErr: false,
70+
},
6171
}
6272
if runtime.GOOS == "linux" {
6373
tests = append(tests, struct {

0 commit comments

Comments
 (0)