我使用C++在tcp中創建了一個服務器和客戶端應用程序。客戶端只是向服務器發送消息。 代碼服務器顯示有關控制檯的客戶端的一些信息:IP地址,端口等 我希望服務器存儲客戶端的IP地址,因爲不同的應用程序,然後將要訪問此列表服務器如何存儲客戶端的IP地址?
怎麼能我存儲連接到服務器的所有客戶端的IP地址? 服務器代碼:
WSADATA wsaData;
SOCKET ListeningSocket, NewConnection;
SOCKADDR_IN ServerAddr, SenderInfo; quantity
int Port = 7171;
char recvbuff[1024];
int ByteReceived, i, nlen;
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket, error code: %ld.\n", WSAGetLastError());
WSACleanup();
return 1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind failed! Error code: %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
if (listen(ListeningSocket, 5) == SOCKET_ERROR)
{
printf("Server: listen: Error listening on socket %ld.\n", WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
return 1;
}
else
{
printf("Server: listening for connections...\n\n");
}
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
printf("Server: New client got connected, ready to receive and send data...\n\n");
ByteReceived = recv(NewConnection, recvbuff, sizeof(recvbuff), 0);
if (ByteReceived > 0)
{
getsockname(ListeningSocket, (SOCKADDR *)&ServerAddr, (int *)sizeof(ServerAddr));
printf("Server: IP(s) used by Server: %s\n", inet_ntoa(ServerAddr.sin_addr));
printf("Server: port used by Server: %d\n\n", htons(ServerAddr.sin_port));
memset(&SenderInfo, 0, sizeof(SenderInfo));
nlen = sizeof(SenderInfo);
getpeername(NewConnection, (SOCKADDR *)&SenderInfo, &nlen);
printf("Server: IP used by Client: %s\n", inet_ntoa(SenderInfo.sin_addr));
printf("Server: Port used by Client: %d\n", htons(SenderInfo.sin_port));
printf("Server: Bytes received: %d\n", ByteReceived);
printf("Server: Message from client: \"");
for(i=0;i < ByteReceived;i++)
{
printf("%c", recvbuff[i]);
}
printf("\"");
}
else if (ByteReceived == 0)
{
printf("Server: Connection closed!\n");
}
else
{
printf("Server: recv failed with error code: %d\n", WSAGetLastError());
}
}
}
你可以只收集INET_NTOA(SenderInfo.sin_addr)爲載體 –
我怎麼做? – user2478375