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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。