FrontierPsycho
FrontierPsycho

Reputation: 743

Which address to use for local TCP server?

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?

Upvotes: 3

Views: 3335

Answers (1)

Luaan
Luaan

Reputation: 63772

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.

Upvotes: 3

Related Questions