我正在编写代码来发现网络上的设备,这只是其中的一部分。
我试图通过在端口 80 上与主机建立套接字连接来发现主机。
它在端口 80 上的某些主机上连接良好,因为设备正在侦听端口 80。有时连接函数会返回错误,WSACONNECTIONREFUSED
因为主机上没有运行 Web 服务。
令人惊讶的是,当我尝试在无效 IP 地址上建立套接字连接时,我得到WSACONNECTIONREFUSED
的不是WSAETIMEDOUT
.
我用谷歌搜索,发现防病毒和防火墙可能导致问题,我在扫描机器上都禁用了,但没有运气可能导致问题的原因是什么?
我已经发布了下面的代码:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR)
{
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return 1;
}
SOCKET ConnectSocket;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET)
{
wprintf(L"socket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("192.168.4.28"); //No Host by this ip address
clientService.sin_port = htons(80); //Port is 80
iResult = connect(ConnectSocket, (SOCKADDR *) &clientService,
sizeof(clientService));
printf("The socket connect return status : %d ", iResult);
if (iResult == SOCKET_ERROR)
{
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR)
wprintf(L"closesocket function failed with error: %ld\n",
WSAGetLastError());
WSACleanup();
return 1;
}
wprintf(L"Connected to server.\n");
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR)
{
printf("\n socket Connection failed ");
WSACleanup();
return 1;
}
WSACleanup();
return 0;
}