最近在一个测试服务器中,我注意到对任何特定端口的bind()函数的调用总是会改变所需的端口并且永远不会失败。
在其他服务器中,一切都按预期工作,
以下是我使用的示例代码
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"Error at WSAStartup()\n");
return 1;
}
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
wprintf(L"socket function failed with error: %u\n", WSAGetLastError());
WSACleanup();
return 1;
}
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("10.10.1.118");
service.sin_port = htons(27500);
iResult = bind(ListenSocket, (SOCKADDR *)&service, sizeof(service));
if (iResult == SOCKET_ERROR) {
wprintf(L"bind failed with error %u\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
else
wprintf(L"bind returned success %i \n", ntohs(service.sin_port));
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
wprintf(L"listen function failed with error: %d\n", WSAGetLastError());
struct sockaddr_in sin;
int addrlen = sizeof(sin);
if (getsockname(ListenSocket, (struct sockaddr *)&sin, &addrlen) == 0 &&
sin.sin_family == AF_INET &&
addrlen == sizeof(sin))
{
int local_port = ntohs(sin.sin_port);
}
wprintf(L"Binding on socket...%d\n", ntohs(sin.sin_port));
每次获取的端口与请求端口(27500)不同。 我用TCPView检查确实侦听端口是绑定任意分配的端口。
有关可能导致此行为的建议吗?