相關前閱讀客戶端的IP地址:C++ Winsock API how to get connecting client IP before accepting the connection?Linux的TCP服務器:接受連接
你好,當你運行的是TCP服務器(C語言編寫的,使用Berkeley套接字API)是有可能在實際接受連接之前讀取客戶端的IP地址/端口?
據我所知,如果您不想通過IP地址與給定的客戶端進行通信,則必須先連接accept
,然後直接連接shutdown
。
僞代碼(我找了peek
和refuse
法):
int serverfd = listen(...);
for(;;) {
struct sockaddr_in clientAddr;
peek(serverfd, &clientAddr, sizeof(clientAddr));
if(isLegit(&clientAddr)) {
int clientfd = accept(serverfd, &clientAddr, sizeof(clientAddr));
handleClient(clientfd);
} else {
refuse(serverfd, &clientAddr, sizeof(clientAddr));
}
}
我做了一大堆研究,因爲我相當肯定,我曾經爲此看到過一個'ioctl'。沒有骰子。我不認爲這也可以做到。 – Omnifarious