TcpClient-如何连接到外部IP地址? [英] TcpClient- how to connect to an external IP address?

查看:417
本文介绍了TcpClient-如何连接到外部IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试设置一个基本方案,其中 TcpClient 连接到同一台机器上的 TcpListener ,但到目前为止它只适用于 127.0.0.1 192.168.XY 。这是我的代码:

I have been trying to setup a basic scenario where a TcpClient connects to a TcpListener on the same machine, but so far it only works for 127.0.0.1 and 192.168.X.Y. Here is my code:

var server = new TcpListener(IPAddress.Any, 51328);

server.Start();

var client = new TcpClient();

client.ConnectAsync(IPAddress.Parse("address from whatismyip"), 51328);

server.AcceptTcpClient(); // hangs indefinitely here

Console.ReadKey();

我从 whatismyip 但我不确定我是否正确地做到了。我的程序有什么不对吗?

I got my external address from whatismyip but I'm not sure if I'm doing it correctly. Is something incorrect with my procedure?

推荐答案

我假设您正在尝试通过互联网连接?如果您通过某些Internet提供商(如COMCAST)连接,那么您可能有一个电缆调制解调器?要做到这一点,你需要在路由器上设置PORT转发。

I am assuming you are trying to connect over the internet? If you are connected via some Internet provider like COMCAST then you probably have a cable modem? To do this sort of thing you are going to need to setup PORT forwarding on a router.

互联网只看你的有线调制解调器,所有你的互联网请求都出去了作为您的有线调制解调器IP,路由器能够代表您转发到192.168.xx地址的数据包,因此为了让您的192.168计算机能够侦听并接受,您必须告诉路由器转发任何消息在端口51328到您的机器。

The internet only see's your cable modem, all your requests to the internet go out as your cable modems IP, the router is able to "route" packets to and from your 192.168.x.x address on your behalf, so in order to have your 192.168 machine be able to listen and accept you must tell your router to forward any messages on port 51328 to your machine.

因此您的代码将使用192.168.x.xx地址侦听端口51328,然后设置路由器。要测试它,您将使用分配给调制解调器的公共互联网地址进行连接。

So your code would listen to port 51328 using the 192.168.x.xx address, then you setup the router. To test it you would connect using the public internet address that is assigned to your modem.

这篇关于TcpClient-如何连接到外部IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆