如何通过IP地址连接计算机

时间:2011-10-16 11:55:50

标签: c# sockets networking

这与c#套接字有关。 我正在开发一个套接字程序。但是我的软件中存在一个问题。 我无法连接到通过本地网络连接到互联网的计算机。但我可以连接到仅使用互联网的计算机。更具描述性, 考虑5台计算机通过使用1个IP地址的调制解调器连接互联网。当我尝试联系其中一台计算机时,A​​PI通过其IP地址连接到调制解调器。但是没有回应。因为调制解调器不响应计算机请求。通过这种方式,我的API必须不只是调制解调器到达计算机。并且抛出了SocketException。我该怎么办这个问题?

2 个答案:

答案 0 :(得分:3)

您遇到的问题是由NAT引起的。允许多个客户端通过一个公共IP地址联机的路由器使用此功能。路由器后面的客户端都不会“知道”或“看到”这个,但它会限制连接。

客户可以发起与外界的连接,但反过来基本上是不可能的。除非您使用port forwarding,否则将一个或多个端口转发到路由器后面的客户端。这样,可以从外部启动连接。

这需要在客户端配置,因此首选的方法是让您的客户端连接到您的服务器,因为这总是可能的(防火墙被忽略)。

*:还有一种解决方法,让客户端连接到您的服务器,然后将连接信息传递给另一个客户端,以便这些客户端可以相互通信。这称为'nat punching',例如,由torrent客户端使用。

答案 1 :(得分:1)

你可以尝试这样的事情......

服务器端代码

namespace Consoleserver
{
class Program
{
    static void Main(string[] args)
    {

        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);


    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );


    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(10);


        while (true)
        {
            Console.WriteLine("Waiting for a connection...");

            Socket handler = listener.Accept();
            Console.WriteLine("connected");
        }

    }
    catch { Console.WriteLine("error"); 
    }
  }
}

客户端代码:

 namespace consoleclient
 {
   class Program
   {
    static void Main(string[] args)
    {
        try
        {

            IPHostEntry ipHostInfo = Dns.Resolve("59.178.131.180");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);


            Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);


            try
            {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected <strong class="highlight">to</strong> {0}",
                    sender.RemoteEndPoint.ToString());
            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                Console.Read();
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
                Console.Read();
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
                Console.Read();
            }

        }
        catch
        { Console.WriteLine("could not <strong class="highlight">connect</strong> A"); }
    }
  }
}

我希望它会帮助你