| // Copyright 2017 The Netstack Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style |
| // license that can be found in the LICENSE file. |
| |
| package ipv4_test |
| |
| import ( |
| "testing" |
| |
| "github.com/google/netstack/tcpip" |
| "github.com/google/netstack/tcpip/header" |
| "github.com/google/netstack/tcpip/link/channel" |
| "github.com/google/netstack/tcpip/link/sniffer" |
| "github.com/google/netstack/tcpip/network/ipv4" |
| "github.com/google/netstack/tcpip/stack" |
| "github.com/google/netstack/tcpip/transport/udp" |
| "github.com/google/netstack/waiter" |
| ) |
| |
| func TestExcludeBroadcast(t *testing.T) { |
| s := stack.New([]string{ipv4.ProtocolName}, []string{udp.ProtocolName}) |
| |
| const defaultMTU = 65536 |
| id, _ := channel.New(256, defaultMTU, "") |
| if testing.Verbose() { |
| id = sniffer.New(id) |
| } |
| if err := s.CreateNIC(1, id); err != nil { |
| t.Fatalf("CreateNIC failed: %v", err) |
| } |
| |
| if err := s.AddAddress(1, ipv4.ProtocolNumber, header.IPv4Broadcast); err != nil { |
| t.Fatalf("AddAddress failed: %v", err) |
| } |
| if err := s.AddAddress(1, ipv4.ProtocolNumber, header.IPv4Any); err != nil { |
| t.Fatalf("AddAddress failed: %v", err) |
| } |
| |
| s.SetRouteTable([]tcpip.Route{{ |
| Destination: "\x00\x00\x00\x00", |
| Mask: "\x00\x00\x00\x00", |
| Gateway: "", |
| NIC: 1, |
| }}) |
| |
| var wq waiter.Queue |
| ep, e := s.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &wq) |
| if e != nil { |
| t.Fatal(e) |
| } |
| |
| randomAddr := tcpip.FullAddress{NIC: 1, Addr: "\x0a\x00\x00\x01", Port: 53} |
| |
| // Cannot connect using a broadcast address as the source. |
| e = ep.Connect(randomAddr) |
| if e == nil { |
| t.Error(`connect succeeded, expected "no route"`) |
| } else if e != tcpip.ErrNoRoute { |
| t.Error(`connect failed with %v, expected "no route"`, e) |
| } |
| |
| // However, we can bind to a broadcast address to listen. |
| e = ep.Bind(tcpip.FullAddress{Addr: header.IPv4Broadcast, Port: 53, NIC: 1}, nil) |
| if e != nil { |
| t.Errorf("bind failed: %v", e) |
| } |
| |
| ep.Close() |
| ep, e = s.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &wq) |
| if e != nil { |
| t.Fatal(e) |
| } |
| |
| // Add a valid primary endpoint address, now we can connect. |
| if err := s.AddAddress(1, ipv4.ProtocolNumber, "\x0a\x00\x00\x02"); err != nil { |
| t.Fatalf("AddAddress failed: %v", err) |
| } |
| e = ep.Connect(randomAddr) |
| if e != nil { |
| t.Errorf("connect failed: %v", e) |
| } |
| } |