Tamir Adler
Tamir Adler

Reputation: 421

Why C# TcpListener need IP address

Why the class TcpListener in C# need an IP address in the constructor? As we just opening a port on the localhost and export it outside.

e.g

public TcpListener(IPAddress localaddr, int port)

The equivalent from java for example, ServerSocket class, don't have such constructor that required IP. Only the port is required.

Upvotes: 4

Views: 1846

Answers (1)

AKX
AKX

Reputation: 169032

The comments really answered this one already – it's there so you have to be explicit about which address to bind to.

If you don't care, IPAddress.Any will do. If you only want local binding, IPAddress.Loopback.

However, to go a bit deeper regarding that ServerSocket you allude to, you can see here that the addressless constructor really just calls the 3-argument constructor with a null address parameter and the docs say

If bindAddr is null, it will default accepting connections on any/all local addresses.

This means that Java's

new ServerSocket(1234)

is equivalent to C#'s

new TcpListener(IPAddress.Any, 1234)

Upvotes: 5

Related Questions