Groups | Blog | Home
all groups > dotnet framework > november 2006 >

dotnet framework : Listening on localhost: how to bind on 2 IP addresses


Samik R.
11/27/2006 3:40:56 PM
I am creating a TCP server app, which will run on a particular machine.
Currently I am using the following code (C#):

LocalHost = Dns.GetHostAddresses("localhost")[0];
Port = 2121;
CommandListener = new TcpListener(LocalHost, Port);
CommandListener.Start();

Naturally, the server is accepting connections at 127.0.0.1:2121. But I
also want it to accept connection at it's actual IP address (e.g.,
192.168.1.111:2121). How might I be able to do that?

Thanks.
Chris Mullins
11/27/2006 3:56:09 PM
Just create an IPAddress that you want to bind to.

Right now, you're binding to "127.0.0.1". You don't want this.

The most common this is to bind to "0.0.0.0" which means, "All".

--
Chris Mullins

[quoted text, click to view]

Peter Duniho
11/27/2006 3:58:10 PM
[quoted text, click to view]

One way is to use INADDR_ANY (or whatever the .NET version of that is...the
actual value is 0, but there's probably a constant that is more correct to
use). Seeing as how you're using the Dns class, there may be something in
that which will return the equivalent. I'm not sure, since all my network
programming has been using Winsock, not .NET.

However you accomplish the above, this will allow your listening socket to
accept connections from any network adapter on the computer. I suppose it's
possible that TcpListener has a way to be created with the equivalent of
INADDR_ANY, but I couldn't tell you off the top of my head what that is. I
recommend reading the "members" portion of the docs for Dns and TcpListener,
as well as the constructors for TcpListener, to see if anything looks
promising.

Pete

Kodali Ranganadh
11/27/2006 7:12:20 PM
Hi Samik,

Replace U r listner constructor with

CommandListener = new TcpListener(Port);

It automatically Accept all type address u given in the Network
interface..

Ranganadh Kodali

[quoted text, click to view]
Samik R.
11/28/2006 10:13:23 AM
I am top-posting, since I am not sure if that is what people do in this
group. Thanks for all the replies and pointers. This is what I did:

static TcpListener CommandListener;
static IPEndPoint LocalHost;
static int Port;

Port = 2121;
LocalHost = new IPEndPoint(IPAddress.Any, Port);
CommandListener = new TcpListener(LocalHost);
CommandListener.Start();

I am using .NET2.0 and C#. I think Ranganadh's version will also work,
but it is deprecated in 2.0. Chris' and Peter's reply helped me in
finding out what I was looking for.

Thanks.
-Samik

[quoted text, click to view]
AddThis Social Bookmark Button