英文:
How can I debug the following Go code, which tries to make a TCP connection to an IP address and port?
问题
我正在从Bittorrent跟踪器获取一个特定种子文件的IP地址和端口号。它代表了Bittorrent网络上的一个节点。我正在尝试使用这段代码连接到该节点。连接总是超时(getsockopt: operation timed out)。我觉得我可能漏掉了一些非常基本的东西,因为我在Python中尝试了相同的代码,结果也是超时。对于每个单独的节点IP地址都会发生这种情况。
我下载了这个Bittorrent客户端 - https://github.com/jtakkala/tulva
它能够使用这种类型的代码(第245行,peer.go)连接到我的系统上的节点。我还能够使用类似的代码连接到在本地主机上运行的TCP服务器。
在JimB的评论和Kenny Grant的回答之后编辑的详细信息:
package main
import (
"fmt"
"net"
)
func main() {
raddr := net.TCPAddr{IP: []byte{}/*这个字节切片包含IP地址*/, Port: int(/*这里是端口号*/)}
conn, err := net.DialTCP("tcp4", nil, &raddr)
if err != nil {
fmt.Println("连接时发生错误", err)
return
}
fmt.Println("已连接到", raddr, conn)
}
英文:
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)
}
答案1
得分: 1
请尝试使用一个已知的有效地址,你会发现你的代码正常工作(例如使用一个4字节的IPv4地址)。BitTorrent节点是短暂存在的,所以如果进行测试,你应该使用你自己知道稳定的IP地址。
raddr := net.TCPAddr{IP: net.IPv4(151, 101, 1, 69), Port: 80}
...
-> 连接到 {151.101.1.69 80}
如果你尝试连接到187.41.59.238:10442,正如jimb所说,该地址不可用。关于IP地址的更多信息,请参考文档:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论