我想使用来自客户端的 IP 地址连接到服务器。要获取我正在使用下面的代码的服务器的 IP 地址,它可以正确检测服务器,但我想在HostEndPoint
事件处理程序设置变量后执行一些其他功能,直到我需要等待我该如何实现它?.. 下面用于扫描的代码是正确的方法吗?如果没有怎么办?
谢谢
int startIp = 0;
int EndIp = 255;
int HostPort = 4678;
string = ipPrefix = "192.168.1.";
EndPoint HostEndPoint;
private void ScanHosts()
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
for (startIP = 0; startIP <= endIP; startIP++)
{
DnsEndPoint endPoint = new DnsEndPoint(ipPrefix + startIP.ToString(), HostPort);
try
{
SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs();
socketEventArgs.RemoteEndPoint = endPoint;
socketEventArgs.UserToken = clientSocket;
socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(socketEventArgs_Connected);
clientSocket.ConnectAsync(socketEventArgs);
}
catch { }
}
}
private void socketEventArgs_Connected(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
HostEndPoint = e.RemoteEndPoint;
}
}