1
0
mirror of https://github.com/veggiedefender/torrent-client.git synced 2025-11-06 09:29:16 +02:00
Files
torrent-client/p2p/p2p.go

48 lines
901 B
Go
Raw Normal View History

2019-12-22 17:43:39 -05:00
package p2p
import (
"encoding/hex"
"fmt"
"net"
"strconv"
"github.com/veggiedefender/torrent-client/message"
)
// Peer encodes information for connecting to a peer
type Peer struct {
IP net.IP
Port uint16
}
// Connect connects to a peer
func Connect(p *Peer, peerID [20]byte, infoHash [20]byte) error {
hostPort := net.JoinHostPort(p.IP.String(), strconv.Itoa(int(p.Port)))
conn, err := net.Dial("tcp", hostPort)
if err != nil {
return err
}
h := message.Handshake{
Pstr: "BitTorrent protocol",
InfoHash: infoHash,
PeerID: infoHash,
}
_, err = conn.Write(h.Serialize())
if err != nil {
return err
}
reply, err := message.ReadHandshake(conn)
if err != nil {
return err
}
fmt.Println("Handshake received:")
fmt.Println(reply.Pstr)
fmt.Println("Peer ID", string(reply.PeerID[:]))
fmt.Println("Hash", hex.EncodeToString(reply.InfoHash[:]))
return nil
}