Question

I got success in sending/receiving data using TCP Sockets over LAN but I want to accomplish the same over the internet. I asked some of my friends and got the idea of using static IP. I was wondering how can I use that static IP? I mean do I need to configure port setting on the host or what?

Below is the sample code I want to use just to give you an idea:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999);
      Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

      socket.Bind(ip);
      socket.Listen(10);
      Console.WriteLine("Waiting for a client...");
      Socket client = socket.Accept();
      IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port);

      string welcome = "Welcome";
      byte[] data = new byte[1024];
      data = Encoding.ASCII.GetBytes(welcome);
      client.Send(data, data.Length,SocketFlags.None);

      Console.WriteLine("Disconnected from {0}",clientep.Address);
      client.Close();
      socket.Close();
   }
}
Was it helpful?

Solution

Once you have the static IP you need to add it as one of the IP's in your network adapter, check out Setting a static IP guide for doing the same.

Then you need to make sure your server socket is listing on this IP, since you are using IPAddress.Any it will bind to all available IP addresses on your system.

Finally you need to explicitly provide the static IP in your client code. Possibly store this IP in a configuration file for changing it at a later stage. If you prefer you can set a custom domain name and point it to the static ip for using it instead of the IP.

OTHER TIPS

Yes, we need configure the port and IP so that we can communicate between two servers. I have done a VPN configuration for this. Please make sure you are able to conneect to that system from where you are trying to run this code. you can run ipconfig/netstat command from command prompt to test this.

Please do this first and make sure both systems are able to talk each other and then please try to run this code. After that still you face the problem, please feel free to contact me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top