I'm trying to write a simple program that will receive a string of max 20 characters and print that string to the screen.
The code compiles, but I get a bind() failed: 10038. After looking up the error number on msdn (socket operation on nonsocket), I changed some code from
int sock;
to
SOCKET sock
which shouldn't make a difference, but one never knows.
Here's the code:
#include <iostream>
#include <winsock2.h>
#include <cstdlib>
using namespace std;
const int MAXPENDING = 5;
const int MAX_LENGTH = 20;
void DieWithError(char *errorMessage);
int main(int argc, char **argv)
{
if(argc!=2){
cerr << "Usage: " << argv[0] << " <Port>" << endl;
exit(1);
}
// start winsock2 library
WSAData wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData)!=0){
cerr << "WSAStartup() failed" << endl;
exit(1);
}
// create socket for incoming connections
SOCKET servSock;
if(servSock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)==INVALID_SOCKET)
DieWithError("socket() failed");
// construct local address structure
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = INADDR_ANY;
servAddr.sin_port = htons(atoi(argv[1]));
// bind to the local address
int servAddrLen = sizeof(servAddr);
if(bind(servSock, (SOCKADDR*)&servAddr, servAddrLen)==SOCKET_ERROR)
DieWithError("bind() failed");
// mark the socket to listen for incoming connections
if(listen(servSock, MAXPENDING)<0)
DieWithError("listen() failed");
// accept incoming connections
int clientSock;
struct sockaddr_in clientAddr;
char buffer[MAX_LENGTH];
int recvMsgSize;
int clientAddrLen = sizeof(clientAddr);
for(;;){
// wait for a client to connect
if((clientSock=accept(servSock, (sockaddr*)&clientAddr, &clientAddrLen))<0)
DieWithError("accept() failed");
// clientSock is connected to a client
// BEGIN Handle client
cout << "Handling client " << inet_ntoa(clientAddr.sin_addr) << endl;
if((recvMsgSize = recv(clientSock, buffer, MAX_LENGTH, 0)) <0)
DieWithError("recv() failed");
cout << "Word in the tubes: " << buffer << endl;
closesocket(clientSock);
// END Handle client
}
}
void DieWithError(char *errorMessage)
{
fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError());
exit(1);
}