联系邮箱: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());
}
}