2021-09-07 18:33:23 +03:00
|
|
|
//go:build aix || darwin || dragonfly || linux || netbsd || solaris
|
|
|
|
// +build aix darwin dragonfly linux netbsd solaris
|
|
|
|
|
|
|
|
package dhcpd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"net"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/insomniacslk/dhcp/dhcpv4"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
)
|
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
func TestDHCPConn_Broadcast(t *testing.T) {
|
2021-09-07 18:33:23 +03:00
|
|
|
b := &bytes.Buffer{}
|
|
|
|
var peers []*net.UDPAddr
|
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
udpConn := &fakePacketConn{
|
2021-09-07 18:33:23 +03:00
|
|
|
writeTo: func(p []byte, addr net.Addr) (n int, err error) {
|
|
|
|
udpPeer, ok := addr.(*net.UDPAddr)
|
|
|
|
require.True(t, ok)
|
|
|
|
|
|
|
|
peers = append(peers, cloneUDPAddr(udpPeer))
|
|
|
|
|
|
|
|
n, err = b.Write(p)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
return n, nil
|
|
|
|
},
|
|
|
|
}
|
2021-09-30 18:28:19 +03:00
|
|
|
conn := &dhcpConn{
|
|
|
|
udpConn: udpConn,
|
|
|
|
bcastIP: net.IP{1, 2, 3, 255},
|
|
|
|
}
|
2021-09-07 18:33:23 +03:00
|
|
|
defaultPeer := &net.UDPAddr{
|
|
|
|
IP: net.IP{1, 2, 3, 4},
|
|
|
|
// Use neither client nor server port.
|
|
|
|
Port: 1234,
|
|
|
|
}
|
2021-09-30 18:28:19 +03:00
|
|
|
respData := (&dhcpv4.DHCPv4{}).ToBytes()
|
2021-09-07 18:33:23 +03:00
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
_, _ = conn.broadcast(respData, cloneUDPAddr(defaultPeer))
|
2021-09-07 18:33:23 +03:00
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
// The same response is written twice but for different peers.
|
|
|
|
assert.EqualValues(t, append(respData, respData...), b.Bytes())
|
2021-09-07 18:33:23 +03:00
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
require.Len(t, peers, 2)
|
2021-09-07 18:33:23 +03:00
|
|
|
|
2021-09-30 18:28:19 +03:00
|
|
|
assert.Equal(t, cloneUDPAddr(defaultPeer), peers[0])
|
|
|
|
assert.Equal(t, &net.UDPAddr{
|
|
|
|
IP: conn.bcastIP,
|
|
|
|
Port: defaultPeer.Port,
|
|
|
|
}, peers[1])
|
2021-09-07 18:33:23 +03:00
|
|
|
}
|