通过Internet上的TCP套接字发送/接收字节(可能使用静态IP) [英] Send/Receive Bytes using TCP Sockets over internet (possibly using static IP)

查看:89
本文介绍了通过Internet上的TCP套接字发送/接收字节(可能使用静态IP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用LAN上的TCP套接字发送/接收数据方面取得了成功,但我想在Internet上完成同样的工作.我问了一些朋友,想到了使用静态IP的想法.我想知道如何使用该静态IP?我的意思是我需要在主机上配置端口设置还是什么?

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

推荐答案

一旦有了静态IP,就需要将其添加为网络适配器中的IP之一,请查看

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.

然后,您需要确保服务器套接字在此IP上列出,因为您正在使用IPAddress.Any,它将绑定到系统上所有可用的IP地址.

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.

最后,您需要在客户端代码中显式提供静态IP.可能将此IP存储在配置文件中,以便以后进行更改.如果愿意,可以设置一个自定义域名,然后将其指向用于使用它的静态IP而不是IP.

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.

这篇关于通过Internet上的TCP套接字发送/接收字节(可能使用静态IP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆