联系邮箱:huxyc@qq.com
//TCP Client
public static string QueryMyPublicNetworkIPbyTcp()
{
string ipstr = string.Empty;
try
{
//1.Socket()
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.Connect()
s.Connect("148.70.217.194", 1002);
//3.Send()
byte[] buf = new byte[50];
string pass = "Please tell me My Public Network IPAddress";
buf = Encoding.ASCII.GetBytes(pass);
s.Send(buf);
////4.Receive()
byte[] data = new byte[50];
s.Receive(data);
ipstr = Encoding.ASCII.GetString(data).TrimEnd('\0');
//5.Close()
s.Shutdown(SocketShutdown.Both);
s.Close();
s.Dispose();
}
catch(Exception ex)
{
ipstr = "服务器异常";
throw ex;
}
return ipstr;
}
static void Main(string[] args)
{
try
{
DateTime time1 = DateTime.Now;
string strip = QueryMyPublicNetworkIPbyTcp();
DateTime time2 = DateTime.Now;
int ms;
if (time2.Millisecond > time1.Millisecond)
ms = time2.Millisecond - time1.Millisecond;
else
ms = 1000 - time2.Millisecond + time1.Millisecond;
Console.WriteLine("{0}ms", ms);
Console.WriteLine("公网IP:{0}",strip);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
本文介绍了一个使用C#编写的TCP客户端程序,该程序能够通过TCP连接到指定服务器查询并获取本机的公网IP地址。文章提供了完整的代码实现,包括建立Socket连接、发送请求、接收响应及解析IP等步骤。
&spm=1001.2101.3001.5002&articleId=88959071&d=1&t=3&u=7a350d4fb11d42519fd31320074443e6)
4532

被折叠的 条评论
为什么被折叠?



