服务器应用程序变坏 ipHostInfo.AddressList[0]

Server application get bad ipHostInfo.AddressList[0]

我有服务器应用程序

如果我 运行 它在服务器应用程序中只是不与客户端通信。我尝试允许所有端口使用防火墙中的端口以及整个应用程序,但它没有帮助。在本地主机上它工作正常。工作系统已正确更新 Win 10。服务器是 windows server 2012.

public void Listen(object data)
    {
  // Establish the local endpoint for the socket.  
    // The DNS name of the computer  
    // running the listener is "host.contoso.com".  
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    // Create a TCP/IP socket.  
    Socket listener = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true)
            {
                // Set the event to nonsignaled state.  
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.  
                Console.WriteLine("Waiting for a connection...at" + localEndPoint.ToString());
                listener.BeginAccept(
                    new AsyncCallback(AcceptCallback),
                    listener);

                // Wait until a connection is made before continuing.  
                allDone.WaitOne();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

看来您应该使用 IPv4 地址。

您可以使用 IPAdress 的AdressFamily property to get a to valid IPv4 Address ("InterNetwork"). Also check isLoopback()

所以,基本上

IPAdress myIp = ipHostInfo
                  .AddressList
                  .Where( a => a.AddressFamily == AddressFamily.InterNetwork)
                  .FirstOrDefault(x => !IPAdress.IsLoopback(x));

有的话应该给你一个不错的

... or as Damien_The_Unbeliever 在评论中非常提醒我: 只需使用 IPAdress.Any 监听 any ip.