title: How does a client communicate with a Windows Service on a machine with multiple adapters?
body: <p>I've inherited a Windows Service + Client application written in C#. The Windows Service opens a TCP/IP socket for listening as follows:</p>
  
  <pre><code>socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  IPHostEntry iphe = Dns.Resolve(Dns.GetHostName());
  socket.Bind(new IPEndPoint(iphe.AddressList[0], ExportServiceRequest.DefaultPort));
  socket.Listen(2);
  // Wait for incoming connections and Accept them.
  </code></pre>
  
  <p>while the client connects as follows:</p>
  
  <pre><code>using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
  {
      IPHostEntry iphe = Dns.Resolve(Dns.GetHostName());
      IPEndPoint ep = new IPEndPoint(iphe.AddressList[0], ExportServiceRequest.DefaultPort);
      socket.Connect(ep);
      // Talk to the server
  }
  </code></pre>
  
  <p>The problem is that on certain machines with multiple network adapters, the 'wrong' adapter is picked by Dns.Resolve(), and the client connection fails.</p>
  
  <p>I am aware that this code is aged and reeking, and haven't coded much raw socket code. Is there a best way to implement a Windows Service listening on a socket, such that at least local connections (from within the same machine) always succeed, regardless of how many network adapters the machine has?</p>
  
  <p>Edit: my question appears poorly formulated. At the end of the day, I want the Windows Service to be accessible by a client, which always is running on the same machine, with no need for configuration. To anthropomorphize, I want the Windows Client to just yell at the server, "what IP address can I talk to you, oh Service running on TCP port ExportServiceRequest.DefaultPort on $LOCALHOST$? I want to talk to you", and have the ensuing TCP/IP conversation just work.</p>