Raymond Raymond

如何用TcpListener监听本机的多个IP地址

event 2009-05-13 visibility 1,420 comment 0 insights
more_vert
insights Stats
如何用TcpListener监听本机的多个IP地址

当我在自己的虚拟机的Windows Server 2003的系统上安装了客户端工具,用主机的IP地址却怎么也无法连接到主机上,即主机上的Windows Service 没能监听到客户端的请求。

于是使用以下代码检查了下主机的Windows Service上的TCP监听器

IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

而这里获得的IP地址其实就是127.0.0.1,这样客户端的任何请求都无法被监听到,这样就失去了这个服务的效用。

为了能让这个TcpListener能同时监听主机上的多个IP地址,比如127.0.0.1 主机的在局域网中的地址192.0.0.1等,只需把创建TcpListener的代码稍作修改就可以了:

// listener = new TcpListener(ipAddress, port);
listener = new TcpListener(IPAddress.Any, port);

这样我在客户端运行就可以获得服务器端的响应了:

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts