smoltcpserver.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #![feature(associated_consts)]
  2. extern crate smoltcp;
  3. use std::env;
  4. use smoltcp::Error;
  5. use smoltcp::phy::{Tracer, TapInterface};
  6. use smoltcp::wire::{EthernetFrame, EthernetAddress, IpAddress, IpEndpoint};
  7. use smoltcp::iface::{SliceArpCache, EthernetInterface};
  8. use smoltcp::socket::{UdpSocket, AsSocket, UdpSocketBuffer, UdpPacketBuffer};
  9. use smoltcp::socket::{TcpListener};
  10. fn main() {
  11. let ifname = env::args().nth(1).unwrap();
  12. let device = TapInterface::new(ifname.as_ref()).unwrap();
  13. let device = Tracer::<_, EthernetFrame<&[u8]>>::new(device);
  14. let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
  15. let endpoint = IpEndpoint::new(IpAddress::default(), 6969);
  16. let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 2048])]);
  17. let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 2048])]);
  18. let udp_socket = UdpSocket::new(endpoint, udp_rx_buffer, udp_tx_buffer);
  19. let tcp_backlog = vec![None];
  20. let tcp_listener = TcpListener::new(endpoint, tcp_backlog);
  21. let hardware_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  22. let protocol_addrs = [IpAddress::v4(192, 168, 69, 1)];
  23. let sockets = [udp_socket, tcp_listener];
  24. let mut iface = EthernetInterface::new(device, arp_cache,
  25. hardware_addr, protocol_addrs, sockets);
  26. loop {
  27. match iface.poll() {
  28. Ok(()) => (),
  29. Err(e) => println!("error {}", e)
  30. }
  31. {
  32. let udp_socket: &mut UdpSocket = iface.sockets()[0].as_socket();
  33. let udp_client = match udp_socket.recv() {
  34. Ok((endpoint, data)) => {
  35. println!("data {:?} from {}", data, endpoint);
  36. Some(endpoint)
  37. }
  38. Err(Error::Exhausted) => {
  39. None
  40. }
  41. Err(e) => {
  42. println!("error {}", e);
  43. None
  44. }
  45. };
  46. if let Some(endpoint) = udp_client {
  47. udp_socket.send_slice(endpoint, "hihihi".as_bytes()).unwrap()
  48. }
  49. }
  50. {
  51. let tcp_listener: &mut TcpListener = iface.sockets()[1].as_socket();
  52. if let Some(stream) = tcp_listener.accept() {
  53. println!("client from {}", stream.remote_end())
  54. }
  55. }
  56. }
  57. }