dongmo3413 2017-03-03 20:42
浏览 56
已采纳

如何调试以下Go代码,该代码试图建立与IP地址和端口的TCP连接?

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条回答 默认 最新

  • drvjlec1767 2017-03-03 21:45
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器