dtc66318 2016-06-14 10:41
浏览 350
已采纳

本地TCP服务器使用哪个地址?

I'm writing a system where two programs will asynchronously communicate over a TCP socket. The client is written in golang, but the server might vary. I'm currently writing one in C#.

During development, I used

conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(d.port)))

for the client, and on the server I did:

this.listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);

However, for production, I suspect that might not work in all cases. For example, the user might use IPv6. I also tried localhost on the server, but on Windows that doesn't seem to be the same as 127.0.0.1 by default (it has to be enabled, which is not an option).

Is there a more fool-proof way of running a local TCP server, that should work in all cases?

  • 写回答

1条回答 默认 最新

  • douquqiang1513 2016-06-14 10:58
    关注

    IPAddress.Loopback is what you're looking for. You still have a separate address for IPv6, though - IPAddress.IPv6Loopback. The two correspond to 127.0.0.1 and ::1 respectively, by definition - it's part of the IP standard.

    If you want to have the server available from other computers as well, IPAddress.Any (and IPAddress.IPv6Any for IPv6) binds to all the NICs on the system.

    In general, there is no way to have a common solution that uses IPv4 and IPv6 "natively", since the two protocols are really entirely separate (with an IPv4 "fallback" in IPv6 - however, it isn't widely supported, and nobody really uses it). This is not a big deal on localhost, though - just try to bind IPAddress.Loopback, and if it fails, try IPAddress.IPv6Loopback.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料