Network data packets can be sent in three ways:Unicast, multicast, and broadcast.
Generally speaking, broadcast enables the packets sent by your machine to be received by all hosts in the same network.
Before explaining how to send broadcast packets, let's take a look at broadcast-related knowledge:
We all know that IP addresses are used to locate a network interface in the network (correct, to be precise, IP addresses are not used to locate a host ). The IP address format we usually see is as follows:
XXX. XXX
This IP address is calledDecimal pointRepresentation, in fact, IP is a 32-bit long binary number, in every 8 bits, divided into four parts, that is, divided into four bytes.
The IP address is composed:[Network number] + [host number]
The network number is used to identify a network, and the host number is used to identify a host in the network (actually an interface on the host ).
Generally, when a computer sends a data packet, it adds the IP address of the sender and the IP address of the receiver to the packet header. However, when a computer sends a data packet, all hosts in the same network will receive the data packet, however, only the computer with the same IP address as the receiver in the data packet will actually receive the data packet.
If you want all computers in the network to receive the packet, set the receiver address of the packet to the highest host number in the network. Generally, 255.255.255.255 can meet this requirement. So if we want to send a UDP broadcast packet, we can try the following example code:
Package mainimport "Net" func main () {// set the sender's IP address here. Check your IP address and set laddr: = net. udpaddr {IP: net. IPv4 (192,168,137,224), Port: 3000,} // set the receiver's IP address to broadcast address raddr: = net. udpaddr {IP: net. IPv4 (255,255,255,255), Port: 3000,} Conn, err: = net. dialudp ("UDP", & laddr, & raddr) If Err! = Nil {println (ERR. Error () return} conn. Write ([] Byte ('Hello peers') Conn. Close ()}
Open Wireshark, set the Filtering Rule to UDP. Port = 3000, and then execute the program to capture the broadcast package we sent:
If reprinted please indicate the source: http://blog.csdn.net/gophers