如果您运行此示例,将看不到端口在netstat
列表中。为什么?我应该如何使其显示?
#include <WinSock.h>
#include <io.h>
#include <stdio.h>
#pragma comment(lib, "WS2_32")
int main() {
WORD wVers = MAKEWORD(2, 2);
WSADATA wsa;
WSAStartup(wVers, &wsa);
SOCKET sock = socket(AF_INET, SOCK_STREAM, 6);
if (sock != INVALID_SOCKET) {
struct sockaddr_in addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int addrlen = sizeof(addr);
bind(sock, (struct sockaddr *)&addr, addrlen);
if (getsockname(sock, (struct sockaddr *)&addr, &addrlen) == 0) {
fprintf(stdout, "HANDLE = %d, port = %d\n", sock, addr.sin_port);
fflush(stdout);
system("netstat -a -n");
}
closesocket(sock);
}
WSACleanup();
}
bind
确实会在 Linux 上立即预留端口。 - ikegami