我终于设法按照上一个线程中提供的建议编写了一个用于主机发现的非阻塞套接字代码。我的发现代码的逻辑是在80,139等端口上与主机建立套接字连接。如果套接字连接是成功则主机存在,或者如果主机通过发送 RST 数据包终止会话,则主机存在。通过使用阻塞套接字,我能够检查来自主机WSACONREFUSED
的RST
数据包,但非阻塞套接字始终返回 0,即使从主机发送 RST 数据包以终止会话也是如此。有没有办法在非阻塞模式下检查 RST 数据包?. 相同的代码如下
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
// Need to link with Ws2_32.lib
#pragma comment(lib, "ws2_32.lib")
int port[]={80,139}; //port number for scanning
int wmain()
{
// Initialize Winsock
WSADATA wsaData;
int i=0,flag=0;
char ip[20];
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return 1;
}
SOCKET socketarray[2];
sockaddr_in clientService;
// Create a SOCKET for connecting to server
for(i=0;i<2;i++){
socketarray[i]=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
}
printf("\n Enter the Ip Address : ");
scanf("%s",ip);
clientService.sin_family = AF_INET;
clientService.sin_addr.S_un.S_addr = inet_addr(ip);
u_long iMode=1;
for(i=0;i<2;i++)
{
ioctlsocket(socketarray[i],FIONBIO,&iMode);
}
fd_set WriteFDs;
FD_ZERO(&WriteFDs);
timeval timer;
timer.tv_sec=5;
timer.tv_usec=5000000;
for(i=0;i<2;i++)
{
FD_SET(socketarray[i],&WriteFDs);
clientService.sin_port = htons((unsigned short)port[i]);
connect(socketarray[i], (SOCKADDR *) & clientService, sizeof(clientService));
iResult=select(0, NULL, &WriteFDs,NULL,&timer);
if(iResult==SOCKET_ERROR||iResult==0)
{
printf("The return value of the function = %d",iResult);
wprintf(L"\n Select failed for the port number %d with error %d ",port[i], WSAGetLastError());
}
else
{
printf("\n The return value of the function = %d",iResult);
wprintf(L"\n Select was success for the port number %d ",port[i]);
}
}
for(i=0;i<2;i++)
{
closesocket(socketarray[i]);
}
WSACleanup();
return 0;
}