我正在编写代码来发现网络上的设备,这只是其中的一部分。
我正在尝试通过在端口80上与主机建立套接字连接来发现主机。
它在端口80上的某些主机上连接良好,因为设备正在侦听端口80.有时 connect 函数返回错误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;
}