Send/Receive Bytes using TCP Sockets over internet (possibly using static IP)

一个人想着一个人 提交于 2019-12-12 19:33:40

问题


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();
   }
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7708855/send-receive-bytes-using-tcp-sockets-over-internet-possibly-using-static-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!