title: Connect C# client to C++ server
body: <p>I just can't get it to work, I'm frustrated.</p>
  
  <p>My C++ code ( <code>_details</code> is <code>addrinfo*</code> and <code>_socket</code> is <code>SOCKET</code>):</p>
  
  <pre><code>struct addrinfo hints;
  _socket = socket(AF_INET, SOCK_STREAM, 0);
  if (_socket &lt; 0)
      throw "Invalid socket";
  ZeroMemory(&amp;hints, sizeof(hints));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_flags = AI_PASSIVE;
  
  
  if (getaddrinfo(NULL, Port.c_str(), &amp;hints, &amp;_details) != 0)
  {
      throw "GetAddrInfo failed";
  }
  
  if ((bind(_socket, _details-&gt;ai_addr, this-&gt;_details-&gt;ai_addrlen)) != 0)
  {
      throw "Bind Unsuccessful";
  }
  
  freeaddrinfo(this-&gt;_details);
  if (listen(this-&gt;_socket, SOMAXCONN) != 0)
          throw "Listen Unsuccessful";
  client = accept(this-&gt;_socket, (struct sockaddr*)&amp;client_addr, &amp;addrlen);
  </code></pre>
  
  <p>A simple C++ server. C++ and Python clients work perfectly with the above server, and doing everything as expected.</p>
  
  <p>Then comes the client:</p>
  
  <pre><code>        Socket s;
  
          IPAddress ip = Dns.GetHostEntry("127.0.0.1").AddressList[0];
          int port = 7777;
          IPEndPoint remoteEP = new IPEndPoint(ip, port);
  
          s = new Socket(AddressFamily.InterNetworkV6,
              SocketType.Stream, ProtocolType.Tcp);
  
          bool isConnected = false;
          while (!isConnected)
          {
              try
              {
                  s.Connect(remoteEP);
                  isConnected = true;
              }
              catch (Exception e1)
              {
                  System.Threading.Thread.Sleep(2000);
              }
          }
  </code></pre>
  
  <p>The C# client works perfectly with a C# server.</p>
  
  <p>Each of these work, together - they just don't. I try to connect to the server but the client always ends up throwing <code>System.Net.Sockets SocketException</code> with the error code of <code>10061</code>, claiming that the C++ server rejects it.</p>
  
  <p>One thread on SO asked a similar question, receiving the answer that he should sleep after every connection request and then try again (as you can see, done already).</p>
  
  <p>Another thread, on another site, claimed that the problem is in the server and that he converted the C++ server parameters from host byte order to network byte order:</p>
  
  <pre><code>listenSocketAddress.sin_port = htons((u_short)port);
  listenSocketAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
  </code></pre>
  
  <p>but I use <code>addrinfo</code> which doesn't contain the same variables as <code>sockaddr_in</code>.</p>
  
  <p>How can I connect those two?</p>