【发布时间】:2013-08-22 07:20:17
【问题描述】:
我终于按照前面thread中提供的建议编写了一个用于主机发现的非阻塞套接字代码。我的发现代码的逻辑是在80,139等端口上与主机建立套接字连接。如果套接字连接成功,则主机存在,或者如果主机通过发送 RST 数据包终止会话,则主机存在。通过使用阻塞套接字,我能够检查来自主机的RST 数据包的WSACONREFUSED,但非阻塞套接字总是返回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;
}
【问题讨论】:
-
您真的想查看是否发送了 RST 数据包吗?或者只是断开连接?对于异步连接,当套接字可写时,您已经完成了连接——无论是否成功。
-
我正在尝试通过建立连接来查找主机是否可用。并且 RST 数据包或 WSCONNREFUSED 指示主机的可用性,根据链接 slashroot.in/what-tcp-ping-and-how-it-used 。如何检查 WSCONNREFUSED 或有更好的检查方法。
标签: sockets