无法使用mono连接到在ubuntu上运行的自己的IPv6 TCP服务器应用程序

时间:2016-11-09 21:53:45

标签: c# tcp mono network-programming ipv6

我的测试基础设施包括3台机器:1台物理机器,其中Windows 10运行hyperv,2台虚拟机安装了ubuntu OS。所有计算机之间都有完整的网络连接(它们相互ping通)。我写了两个简单的C#程序:TCP客户端和TCP服务器(下面我附上了重现问题的最小代码)。当我在Windows机器上运行客户端和其中一台ubuntu机器上的服务器时,一切正常。但是当我尝试在其他ubuntu机器上的某个ubuntu机器和服务器上运行客户端时,我在客户端遇到错误:

  

TCPClientTest.exe信息:0:System.Net.Sockets.SocketException(0x80004005):参数无效     在System.Net.Sockets.TcpClient.Connect(System.Net.IPAddress [] ipAddresses,System.Int32 port)[0x000e9] in< 59be416de143456b88b9988284f43350&gt ;:0     在System.Net.Sockets.TcpClient.Connect(System.String hostname,System.Int32 port)[0x00007] in< 59be416de143456b88b9988284f43350&gt ;:0     在System.Net.Sockets.TcpClient..ctor(System.String hostname,System.Int32 port)[0x00006] in< 59be416de143456b88b9988284f43350&gt ;:0     在TCPClientTest.Program.Main(System.String [] args)[0x00002] in:0       日期时间= 2016-11-09T21:25:42.4641950Z

TCP客户端:

TcpClient client = new TcpClient("fe80::3", 15000);
NetworkStream stream = client.GetStream();
int number = stream.ReadByte();
stream.Close();
client.Close();

TCP服务器:

TcpListener server = new TcpListener(IPAddress.IPv6Any, 15000);
server.Start();

TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
stream.WriteByte(199);
stream.Close();
client.Close();

Ubuntu版本:16.04 LTS

单声道版本:4.6 Service Release 0.1(4.6.1.5)

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。 IPv6链路本地地址与称为范围ID的数字相关联,该数字指定了我们要用于连接的网络接口。看起来在Linux系统中我们必须明确地提供这些信息(即使使用ping6我们也需要这样做)但是在Windows上没有这样的要求,根据本文https://technet.microsoft.com/pl-pl/ms739166它正在使用邻居发现并尝试获得正确的我们的界面。

例如: 在Windows ping fe80::3上工作正常但在Linux上我们需要执行ping6 -I eth0 fe80::3ping6 fe80::3%2

必须稍微修改TCP客户端以尊重范围ID并指定它将用于正常工作的网络接口:

IPAddress ipAddress = null;

foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    IPInterfaceProperties ipIntProperties = networkInterface.GetIPProperties();
    foreach (UnicastIPAddressInformation addr in ipIntProperties.UnicastAddresses)
    {
        String addressWithoutScopeId = addr.Address.ToString().Split('%')[0];
        if (addressWithoutScopeId.Equals("fe80::2"))
        {
            ipAddress = addr.Address;
            break;
         }

     }
     if (ipAddress != null)
         break;
}

var endPoint = new IPEndPoint(ipAddress, 0);
TcpClient client = new TcpClient(endPoint);
client.Connect(IPAddress.Parse("fe80::3"), 15000);
NetworkStream stream = client.GetStream();
int number = stream.ReadByte();
stream.Close();
client.Close();