Created
July 28, 2018 14:13
-
-
Save jkilpatr/3bb1ef759007f367ab357aab014ecb32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate byteorder; | |
extern crate bytes; | |
extern crate failure; | |
extern crate regex; | |
use bytes::BufMut; | |
use bytes::BytesMut; | |
use failure::Error; | |
use regex::Regex; | |
use std::io; | |
use std::io::Cursor; | |
use std::net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6, UdpSocket}; | |
use std::time::Duration; | |
// Random header to verify | |
pub const MSG_IM_HERE: u32 = 0x5b6d4158; | |
fn encode_im_here(addr: Ipv6Addr) -> Vec<u8> { | |
let mut buf = Vec::new(); | |
buf.put_u32_be(MSG_IM_HERE); | |
buf.put_u16_be(22); | |
let ipaddr_bytes: [u8; 16] = addr.octets(); | |
for i in 0..15 { | |
buf.put_u8(ipaddr_bytes[i]); | |
} | |
buf | |
} | |
fn main() { | |
let port: u16 = 4876; | |
println!("About to send ImHere"); | |
let disc_ip = Ipv6Addr::new(0xff02, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x8); | |
loop { | |
let link_ip = "fe80::8379:a4a7:130b:2554".parse::<Ipv6Addr>(); | |
if link_ip.is_err() { | |
continue; | |
} | |
let link_ip = link_ip.unwrap(); | |
let source_socketaddr = SocketAddrV6::new(link_ip, port.into(), 0, 2); | |
let source_socket = UdpSocket::bind(source_socketaddr).expect(&format!( | |
"Failed to bind to link local address {:?} on {:?}", | |
link_ip, 1 | |
)); | |
let multicast_socketaddr = | |
SocketAddrV6::new("ff02:0:0:0:0:0:1:8".parse().unwrap(), port.into(), 0, 2); | |
println!("Joining broadcast {:?}", source_socket.set_broadcast(true)); | |
println!( | |
"Joining multicast loop {:?}", | |
source_socket.set_multicast_loop_v6(true) | |
); | |
println!( | |
"Joining multicast v6 group {:?}", | |
source_socket.join_multicast_v6(&disc_ip, 2) | |
); | |
let dest_socket = | |
UdpSocket::bind(multicast_socketaddr).expect("failed to bind to multicast!"); | |
println!( | |
"Joining multicast loop {:?}", | |
dest_socket.set_multicast_loop_v6(true) | |
); | |
println!( | |
"Joining multicast v6 group {:?}", | |
dest_socket.join_multicast_v6(&disc_ip, 2) | |
); | |
println!( | |
"Setting read timeout {:?}", | |
dest_socket.set_read_timeout(Some(Duration::new(2, 0))) | |
); | |
let result = source_socket.send_to(&encode_im_here(link_ip.clone()), multicast_socketaddr); | |
println!("Sending ImHere to broadcast gets {:?}", result); | |
let mut buf: [u8; 1500] = [0; 1500]; | |
let res = dest_socket.recv(&mut buf); | |
println!("Trying to read from the sending socket {:?}", res); | |
if !res.is_err() { | |
println!("Data read from socket {:?}", buf.to_vec()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment