C#公共IP客户端/服务器

时间:2017-10-20 06:54:57

标签: c# sockets ipv4

出于研究目的,我开发了一个在我的本地网络上工作的异步服务器/客户端应用程序。但现在我想让它能够连接到我的公共IP,所以我的服务器可以从任何地方访问。

以下是服务器代码的相关部分,它似乎工作正常:

    static void Main(string[] args)
    {
            AsyncServer server = new AsyncServer(60101);
            server.RunAsync();
            Console.Read();
    }

public class AsyncServer
{
    private IPAddress ipAddress;
    private int port;

    public AsyncServer(int port)
    {
        this.port = port;
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        this.ipAddress = null;
        for (int i = 0; i < ipHostInfo.AddressList.Length; i++)
        {
            if (ipHostInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
            {
                this.ipAddress = ipHostInfo.AddressList[i];
                break;
            }
        }
        if (this.ipAddress == null)
            throw new Exception("No IPv4 address for server.");
    }

    public async void RunAsync()
    {
        TcpListener tcpListener = new TcpListener(this.ipAddress, this.port);
        tcpListener.Start();

以下是客户端代码的相关部分。这是它无法连接的地方。

    static void Main(string[] args)
    {
            AsyncClient client = new AsyncClient("MyPublicIP", 60101);
            client.ConnectAsync().Wait();
            Console.Read();
    }
}

public class AsyncClient
{
    private IPAddress ipAddress;
    private int port;

    public AsyncClient(string ip, int port)
    {
        this.port = port;
        IPAddress.TryParse(ip, out ipAddress);
    }

    public async Task ConnectAsync()
    {
        int attempts = 0;
        TcpClient client = new TcpClient();
        while (!client.Connected)
        {
            try
            {
                attempts++;
                client.Connect(this.ipAddress, this.port);
                Console.Clear();
                Console.WriteLine("Connected");
                await ProcessAssync(client);
            }
            catch (SocketException)
            {
                Console.Clear();
                Console.WriteLine("Connection Attempts: {0}", attempts);

我已经在我的路由器上将端口转发到我的本地服务器IP&#34; 192.168.254.1&#34;对于使用过的端口&#34; 60101&#34;,但没有任何改变,他只是在那里尝试了一段时间然后连接失败。

2 个答案:

答案 0 :(得分:0)

您真的希望/需要限制服务器只能在一个界面上收听吗?

当您仅使用端口号启动TcpListener但没有IP地址时,TcpListener将侦听所有接口。使用您的代码,TcpListener将使用IPv4 IP地址在第一个接口上监听。但这可能是您的路由器无法使用的接口(例如,虚拟化主机提供的内部接口)。

我会将服务器代码更改为:

public class AsyncServer
{
    private int port;

    public AsyncServer(int port)
    {
        this.port = port;
    }

    public async void RunAsync()
    {
        TcpListener tcpListener = new TcpListener(IPAddress.Any, this.port);
        tcpListener.Start();

答案 1 :(得分:-2)

尝试http://www.whatsmyip.org/并解析该IP。对于服务器,也许最好使用IPAddress.Any