dtc66318 2016-06-14 02:41
浏览 351
已采纳

本地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 02: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部