Created
March 20, 2026 19:50
-
-
Save hernandohhoyos/c7625e6c239b261f0820c9967e7962b1 to your computer and use it in GitHub Desktop.
P2P Con Servicio de Descubrimiento mDNS en Golang
This file contains hidden or 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
| package main | |
| import ( | |
| "context" | |
| "crypto/rand" | |
| "fmt" | |
| "os" | |
| "os/signal" | |
| "syscall" | |
| "time" | |
| "github.com/libp2p/go-libp2p" | |
| "github.com/libp2p/go-libp2p/core/crypto" | |
| "github.com/libp2p/go-libp2p/core/host" | |
| "github.com/libp2p/go-libp2p/core/peer" | |
| "github.com/libp2p/go-libp2p/p2p/discovery/mdns" | |
| "github.com/libp2p/go-libp2p/p2p/protocol/ping" | |
| "github.com/libp2p/go-libp2p/p2p/transport/tcp" | |
| ) | |
| const ( | |
| DiscoveryServiceTag = "go-P2P-mDNS-demo" | |
| ) | |
| func main() { | |
| // 1. Generación de identidad (en producción esto debería ser persistente) | |
| privKey, _, err := crypto.GenerateEd25519Key(rand.Reader) | |
| if err != nil { | |
| panic(err) | |
| } | |
| // Iniciamos el nodo en un puerto aleatorio. | |
| node, err := libp2p.New( | |
| libp2p.Identity(privKey), | |
| libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/0"), | |
| libp2p.Ping(false), | |
| libp2p.Transport(tcp.NewTCPTransport, tcp.DisableReuseport()), | |
| ) | |
| // 3. Configurar protocolo de ping e imprimir info básica | |
| pingService := &ping.PingService{Host: node} | |
| node.SetStreamHandler(ping.ID, pingService.PingHandler) | |
| fmt.Println("Tu PeerID:", node.ID().String()) | |
| fmt.Println("Mis direcciones:", node.Addrs()) | |
| // 4. Configurar mDNS para descubrimiento. | |
| mdnsService := mdns.NewMdnsService(node, DiscoveryServiceTag, &discoveryNotifee{h: node}) | |
| if err := mdnsService.Start(); err != nil { | |
| panic(err) | |
| } | |
| // 5. Esperar señal de cierre | |
| ch := make(chan os.Signal, 1) | |
| signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) | |
| <-ch | |
| fmt.Println("\nCerrando nodo...") | |
| node.Close() | |
| } | |
| // discoveryNotifee es la estructura que maneja los eventos de descubrimiento de mDNS. | |
| type discoveryNotifee struct { | |
| h host.Host | |
| } | |
| // HandlePeerFound se llama automáticamente cada vez que mDNS encuentra otro nodo. | |
| func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) { | |
| // Evitamos conectarnos a nosotros mismos | |
| if pi.ID == n.h.ID() { | |
| return | |
| } | |
| fmt.Printf("¡Nodo encontrado!: %s. Conectando...\n", pi.ID.String()) | |
| // Intentamos conectar al nodo descubierto | |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| defer cancel() | |
| if err := n.h.Connect(ctx, pi); err != nil { | |
| fmt.Printf("Error al conectar con el nodo %s: %v\n", pi.ID.String(), err) | |
| } else { | |
| fmt.Printf("Conectado con éxito al nodo %s\n", pi.ID.String()) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment