title: C# Public IP Client/Server
body: <p>For study purpose I've developed an async server/client application working on my local network. But now I want to make it able to connect to my public ip instead, so my server can be accessible from anywhere.</p>
  
  <p>Here is relevant parts of Server Code, it seems to be working just fine:</p>
  
  <pre><code>    static void Main(string[] args)
      {
              AsyncServer server = new AsyncServer(60101);
              server.RunAsync();
              Console.Read();
      }
  
  public class AsyncServer
  {
      private IPAddress ipAddress;
      private int port;
  
      public AsyncServer(int port)
      {
          this.port = port;
          IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
          this.ipAddress = null;
          for (int i = 0; i &lt; ipHostInfo.AddressList.Length; i++)
          {
              if (ipHostInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
              {
                  this.ipAddress = ipHostInfo.AddressList[i];
                  break;
              }
          }
          if (this.ipAddress == null)
              throw new Exception("No IPv4 address for server.");
      }
  
      public async void RunAsync()
      {
          TcpListener tcpListener = new TcpListener(this.ipAddress, this.port);
          tcpListener.Start();
  </code></pre>
  
  <p>Here is relevant parts of Client Code. Here is where it fails to connect.</p>
  
  <pre><code>    static void Main(string[] args)
      {
              AsyncClient client = new AsyncClient("MyPublicIP", 60101);
              client.ConnectAsync().Wait();
              Console.Read();
      }
  }
  
  public class AsyncClient
  {
      private IPAddress ipAddress;
      private int port;
  
      public AsyncClient(string ip, int port)
      {
          this.port = port;
          IPAddress.TryParse(ip, out ipAddress);
      }
  
      public async Task ConnectAsync()
      {
          int attempts = 0;
          TcpClient client = new TcpClient();
          while (!client.Connected)
          {
              try
              {
                  attempts++;
                  client.Connect(this.ipAddress, this.port);
                  Console.Clear();
                  Console.WriteLine("Connected");
                  await ProcessAssync(client);
              }
              catch (SocketException)
              {
                  Console.Clear();
                  Console.WriteLine("Connection Attempts: {0}", attempts);
  </code></pre>
  
  <p>I've already made port forwarding on my router to my local server IP "192.168.254.1" to the used port "60101", but nothing changes, he just keeps there trying for a while then fails the connection.</p>