title: connect to other computer that is not local
body: <p>I try to connect from my pc to other pc what I have at home and both are connected to the internet. So I check the other pc with the program MyIpAdress and it is like: <code>38.xx.xx.xx.</code>
  And I have this program:The server:</p>
  
  <pre><code>public delegate void StatusChangedHandler(object sender, StatusChangedEventArgs e);
  
      public class StatusChangedEventArgs : EventArgs
      {
          // This will store our only parameter / event argument, which is the event message
          private string EventMsg;
  
          // We need to define this property in order to retrieve the message in the event handler, back in Form1.cs
          public string EventMessage
          {
              get
              {
                  return EventMsg;
              }
          }
  
          // The constructor will set the message
          public StatusChangedEventArgs(string strEventMsg)
          {
              EventMsg = strEventMsg;
          }
      }
  
      class Monitor
      {
          // Will store the IP address passed to it
          IPAddress ipAddress;
  
          // The constructor sets the IP address to the one retrieved by the instantiating object
          public Monitor(IPAddress address)
          {
              ipAddress = address;
          }
  
          // Declare the event that we'll fire later
          public event StatusChangedHandler StatusChangedEvent;
          // The thread that will hold the connection listener
          private Thread thrListener;
          // The TCP object that listens for connections
          private TcpListener tlsServer;
          // The thread that will send information to the client
          private Thread thrSender;
          // Will tell the while loop to keep monitoring for connections
          bool ServRunning = false;
  
          public void StartMonitoring()
          {
              // Get the IP of the first network device, however this can prove unreliable on certain configurations
              IPAddress ipaLocal = ipAddress;
              if (tlsServer == null)
              {
                  // Create the TCP listener object using the IP of the server and the specified port
                  tlsServer = new TcpListener(ipaLocal, 1986  );
              }
              // Start the TCP listener and listen for connections
              tlsServer.Start();
  
              // The while loop will check for true in this before checking for connections
              ServRunning = true;
  
              // Start the new tread that hosts the listener
              thrListener = new Thread(KeepListening);
              thrListener.Start();
          }
  
          private void KeepListening()
          {
              TcpClient tclServer;
              // While the server is running
              while (ServRunning == true)
              {
                  // Accept a pending connection
                  tclServer = tlsServer.AcceptTcpClient();
                  // Start a new thread where our new client who just connected will be managed
                  thrSender = new Thread(new ParameterizedThreadStart(AcceptClient));
                  // The thread calls the AcceptClient() method
                  thrSender.Start(tclServer);
              }
          }
  
          // Occures when a new client is accepted
          private void AcceptClient(object newClient)
          {
              // Set the argument/parameter to a message explaining what just happened
              StatusChangedEventArgs evArg = new StatusChangedEventArgs("A client was successfully accepted.");
              // Fire the event because a new client was accepted
              StatusChangedEvent(this, evArg);
          }
      }
  </code></pre>
  
  <p>But if I fill in in the textbox the ipadress: <code>38.xxx.xxx.xx</code>,<br>
  I will get this error:</p>
  
  <blockquote>
    <p>An unhandled exception of type 'System.Net.Sockets.SocketException'
    occurred in System.dll
    Additional information: The requested address is not valid in its context</p>
  </blockquote>
  
  <p>So it can only see Local ipAdresses?<br>
  But how to change it, that it also finds not local Ipadresses?</p>
  
  <p>And this is the client application:</p>
  
  <p>public partial class Form1 : Form
      {</p>
  
  <pre><code>    private string UserName = "Unknown";
      private StreamWriter swSender;
      private StreamReader srReceiver;
      private TcpClient tcpServer;
      // Needed to update the form with messages from another thread
      private delegate void UpdateLogCallback(string strMessage);
      // Needed to set the form to a "disconnected" state from another thread
      private delegate void CloseConnectionCallback(string strReason);
      private Thread thrMessaging;
      private IPAddress ipAddr;
      private bool Connected;
  
      public Form1()
      {
          Application.ApplicationExit += new EventHandler(OnApplicationExit);
          InitializeComponent();
      }
  
      private void button1_Click(object sender, EventArgs e)
      {
          // If we are not currently connected but awaiting to connect
          if (Connected == false)
          {
              // Initialize the connection
              InitializeConnection();
          }
          else // We are connected, thus disconnect
          {
              CloseConnection("Disconnected at user's request.");
          }
      }
  
      private void ReceiveMessages()
      {
          // Receive the response from the server
          srReceiver = new StreamReader(tcpServer.GetStream());
          // If the first character of the response is 1, connection was successful
          string ConResponse = srReceiver.ReadLine();
          // If the first character is a 1, connection was successful
          if (ConResponse[0] == '1')
          {
              // Update the form to tell it we are now connected
              this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" });
          }
          else // If the first character is not a 1 (probably a 0), the connection was unsuccessful
          {
              string Reason = "Not Connected: ";
              // Extract the reason out of the response message. The reason starts at the 3rd character
              Reason += ConResponse.Substring(2, ConResponse.Length - 2);
              // Update the form with the reason why we couldn't connect
              this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
              // Exit the method
              return;
          }
          // While we are successfully connected, read incoming lines from the server
          while (Connected)
          {
              // Show the messages in the log TextBox
              this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
          }
      }
      private void InitializeConnection()
      {
          // Parse the IP address from the TextBox into an IPAddress object
          ipAddr = IPAddress.Parse(txtServerIP.Text);
          // Start a new TCP connections to the chat server
          tcpServer = new TcpClient();
          tcpServer.Connect(IPAddress.Any, 1986);
  
          // Helps us track whether we're connected or not
          Connected = true;
          // Prepare the form
          UserName = txtUserName.Text;
  
          // Disable and enable the appropriate fields
          txtServerIP.Enabled = false;
          txtUserName.Enabled = false;
          txtMessage.Enabled = true;
          btnSend.Enabled = true;
          btnConnect.Text = "Disconnect";
  
          // Send the desired username to the server
          swSender = new StreamWriter(tcpServer.GetStream());
          swSender.WriteLine(txtUserName.Text);
          swSender.Flush();
  
          // Start the thread for receiving messages and further communication
          thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
          thrMessaging.Start();
      }
      private void UpdateLog(string strMessage)
      {
          // Append text also scrolls the TextBox to the bottom each time
          txtLog.AppendText(strMessage + "\r\n");
      }
  
      private void btnSend_Click(object sender, EventArgs e)
      {
          SendMessage();
      }
  
      private void SendMessage()
      {
          if (txtMessage.Lines.Length &gt;= 1)
          {
              swSender.WriteLine(txtMessage.Text);
              swSender.Flush();
              txtMessage.Lines = null;
          }
          txtMessage.Text = "";
      }
      // Closes a current connection
      private void CloseConnection(string Reason)
      {
          // Show the reason why the connection is ending
          txtLog.AppendText(Reason + "\r\n");
          // Enable and disable the appropriate controls on the form
          txtServerIP.Enabled = true;
          txtUserName.Enabled = true;
          txtMessage.Enabled = false;
          btnSend.Enabled = false;
          btnConnect.Text = "Connect";
  
          // Close the objects
          Connected = false;
          swSender.Close();
          srReceiver.Close();
          tcpServer.Close();
      }
      public void OnApplicationExit(object sender, EventArgs e)
      {
          if (Connected == true)
          {
              // Closes the connections, streams, etc.
              Connected = false;
              swSender.Close();
              srReceiver.Close();
              tcpServer.Close();
          }
      }
  }
  </code></pre>
  
  <p>So I changed this line:</p>
  
  <p>tcpServer.Connect(IPAddress.Any, 1986);</p>
  
  <p>but If I run the server application I will get this error:</p>
  
  <p>I get the same error as by the client:</p>
  
  <p>An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll</p>
  
  <p>Additional information: The requested address is not valid in its context</p>
  
  <p>Thank you</p>
  
  <p>I show you two Images:This is the Server app. That works
  <a href="https://i.stack.imgur.com/HSvUk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HSvUk.png" alt="enter image description here"></a></p>
  
  <p>This is the Client app, that doesnt work:
  <a href="https://i.stack.imgur.com/nXhvL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nXhvL.png" alt="enter image description here"></a></p>
  
  <p>And if I change the code in the client app, like this:</p>
  
  <p>tcpServer.Connect(ipAddr, 1986); Then I will get this error:</p>
  
  <p>Additional information: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond</p>
  
  <p>But I can pin the other pc</p>
  
  <p>In the client program I have this:</p>
  
  <pre><code>  private void InitializeConnection()
          {
              // Parse the IP address from the TextBox into an IPAddress object
              ipAddr = IPAddress.Parse(txtServerIP.Text);
              // Start a new TCP connections to the chat server
              tcpServer = new TcpClient();
              tcpServer.Connect(IPAddress.Any, 1986);
  
              // Helps us track whether we're connected or not
              Connected = true;
              // Prepare the form
              UserName = txtUserName.Text;
  
              // Disable and enable the appropriate fields
              txtServerIP.Enabled = false;
              txtUserName.Enabled = false;
              txtMessage.Enabled = true;
              btnSend.Enabled = true;
              btnConnect.Text = "Disconnect";
  
              // Send the desired username to the server
              swSender = new StreamWriter(tcpServer.GetStream());
              swSender.WriteLine(txtUserName.Text);
              swSender.Flush();
  
              // Start the thread for receiving messages and further communication
              thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
              thrMessaging.Start();
          }
  </code></pre>
  
  <p>what I have to change then?</p>