1+ use socket2:: { Domain , Protocol , Socket , Type } ;
2+ use std:: io:: Result ;
3+ use std:: net:: { SocketAddr , SocketAddrV4 , UdpSocket } ;
4+
5+ mod protocol;
6+
7+ pub const PORT : u16 = 1200 ;
8+
9+ pub struct UdpBroadcast {
10+ socket : UdpSocket ,
11+ target : SocketAddr ,
12+ }
13+
14+ impl UdpBroadcast {
15+ pub fn new ( ) -> Result < Self > {
16+ Self :: with_port ( PORT , PORT )
17+ }
18+
19+ pub fn with_port ( send : u16 , receive : u16 ) -> Result < Self > {
20+ let socket = Socket :: new ( Domain :: IPV4 , Type :: DGRAM , Some ( Protocol :: UDP ) ) ?;
21+ socket. set_broadcast ( true ) ?;
22+ socket. set_reuse_address ( true ) ?;
23+
24+ let addr: SocketAddr = ( [ 0 , 0 , 0 , 0 ] , receive) . into ( ) ; // 0.0.0.0 != 192.168.x.x.. 미래의 나, 해결해라!
25+ socket. bind ( & addr. into ( ) ) ?;
26+
27+ let socket: UdpSocket = socket. into ( ) ;
28+
29+ Ok ( Self {
30+ socket,
31+ target : ( [ 255 , 255 , 255 , 255 ] , send) . into ( ) , // 브로드캐스트 주소 바꿀 것
32+ } )
33+ }
34+
35+ pub fn send ( & self , data : & [ u8 ] ) -> Result < usize > {
36+ self . socket . send_to ( data, self . target )
37+ }
38+
39+ pub fn recv ( & self , buf : & mut [ u8 ] ) -> Result < ( usize , SocketAddr ) > {
40+ self . socket . recv_from ( buf)
41+ }
42+
43+ pub fn is_self ( & self , addr : SocketAddr ) -> bool {
44+ addr == self . target
45+ }
46+ }
47+
48+ #[ cfg( test) ]
49+ mod tests {
50+ use std:: thread;
51+ use std:: time:: Duration ;
52+ use crate :: network:: UdpBroadcast ;
53+
54+ #[ test]
55+ fn test_broadcast ( ) {
56+ let node1 = UdpBroadcast :: new ( ) . unwrap ( ) ;
57+ let node2 = UdpBroadcast :: new ( ) . unwrap ( ) ;
58+ let data: [ u8 ; 4 ] = [ 0x43 , 0x55 , 0x54 , 0x45 ] ;
59+ let mut receive_buffer = [ 0u8 ; 4 ] ;
60+
61+ let receiver = thread:: scope ( |scope| {
62+ let result = scope. spawn ( || {
63+ thread:: sleep ( Duration :: from_secs ( 1 ) ) ;
64+ node2. recv ( & mut receive_buffer) . unwrap ( )
65+ } ) ;
66+ scope. spawn ( || {
67+ node1. send ( & data) . unwrap ( ) ;
68+ } ) ;
69+ result. join ( ) . unwrap ( )
70+ } ) ;
71+ let ( receive_count, sender_address) = receiver;
72+
73+ assert_eq ! ( receive_count, data. len( ) ) ;
74+ assert_eq ! ( receive_buffer, data) ;
75+
76+ }
77+
78+ }
0 commit comments