简体   繁体   中英

How can I debug the following Go code, which tries to make a TCP connection to an IP address and port?

I am getting an IP address and port number from a Bittorrent tracker, for a specific torrent file. It represents a peer on the bittorrent network. I am trying to connect to the peer using this code. The connection always times out (getsockopt: operation timed out). I think I am missing something very fundamental here, because I tried the same code in python with the exact same result, operation timed out. It happens for every single peer IP address.

I downloaded this bittorrent client - https://github.com/jtakkala/tulva which is able to connect to peers from my system using this type of code (Line 245, peer.go). I have also been able to use similar code for connecting to a tcp server running on localhost.

Edited details after JimB's comment and Kenny Grant's answer

package main

import (
    "fmt"
    "net"
)

func main() {
    raddr := net.TCPAddr{IP: []byte{}/*This byte slice contains the IP*/, Port: int(/*Port number here*/)}
    conn, err := net.DialTCP("tcp4", nil, &raddr)
    if err != nil {
        fmt.Println("Error while connecting", err)
        return
    }
    fmt.Println("Connected to ", raddr, conn)
}

Try it with a known good address, and you'll see your code works fine (with a 4 byte IPv4 address for SO say). Bittorrent peers are transient, so it probably just went away, if testing you should use your own IPs that you know are stable.

raddr := net.TCPAddr{IP: net.IPv4(151, 101, 1, 69), Port: int(80)}
...
-> Connected to  {151.101.1.69 80 }

if you're trying to connect to 187.41.59.238:10442, as jimb says, it's not available. For IPs, see the docs:

https://sourcegraph.com/github.com/golang/go@9fd359a29a8cc55ed665542d2a3fe9fef8baaa7d/-/blob/src/net/ip.go#L32:6-32:8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM