1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
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);
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
std::vector<std::string> vClientIPs; // client ip string vector
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));
vClientIPs.push_back(std::string(inet_ntoa(ServerAddr.sin_addr))); //insert client ip
//need to send vector to client
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());
}
}
}
}
| |