identify_example/main.rs
1// Copyright 2018 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21#![doc = include_str!("../README.md")]
22
23use std::error::Error;
24
25use futures::StreamExt;
26use libp2p::{core::multiaddr::Multiaddr, identify, noise, swarm::SwarmEvent, tcp, yamux};
27use tracing_subscriber::EnvFilter;
28
29#[tokio::main]
30async fn main() -> Result<(), Box<dyn Error>> {
31 let _ = tracing_subscriber::fmt()
32 .with_env_filter(EnvFilter::from_default_env())
33 .try_init();
34
35 let mut swarm = libp2p::SwarmBuilder::with_new_identity()
36 .with_tokio()
37 .with_tcp(
38 tcp::Config::default(),
39 noise::Config::new,
40 yamux::Config::default,
41 )?
42 .with_behaviour(|key| {
43 identify::Behaviour::new(identify::Config::new(
44 "/ipfs/id/1.0.0".to_string(),
45 key.public(),
46 ))
47 })?
48 .build();
49
50 // Tell the swarm to listen on all interfaces and a random, OS-assigned
51 // port.
52 swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
53
54 // Dial the peer identified by the multi-address given as the second
55 // command-line argument, if any.
56 if let Some(addr) = std::env::args().nth(1) {
57 let remote: Multiaddr = addr.parse()?;
58 swarm.dial(remote)?;
59 println!("Dialed {addr}")
60 }
61
62 loop {
63 match swarm.select_next_some().await {
64 SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
65 // Prints peer id identify info is being sent to.
66 SwarmEvent::Behaviour(identify::Event::Sent { peer_id, .. }) => {
67 println!("Sent identify info to {peer_id:?}")
68 }
69 // Prints out the info received via the identify event
70 SwarmEvent::Behaviour(identify::Event::Received { info, .. }) => {
71 println!("Received {info:?}")
72 }
73 _ => {}
74 }
75 }
76}