Hey, I wrote a test program for my current project... all it's supposed to do is loop 2000 times: create 50 sockets->connect them->receive on them->close them
I don't see anything wrong with the code, but since I'm getting runtime errors I just want to be sure that nothing's wrong with the testing code itself. Can someone skim through this and make sure I haven't done anything stupid? Thanks
Code:
std::vector<SOCKET> socks;
//Stick 50 SOCKET's in a vector
for(int i = 0; i < 50; ++i) //Connect with 50 sockets at a time
{
socks.push_back(SOCKET());
}
//Fill a sockaddr with the local machine's address
SOCKADDR_IN saddr;
HOSTENT* h = gethostbyname("localhost");
saddr.sin_addr.s_addr = *(unsigned long*)h->h_addr_list[0];
saddr.sin_family = AF_INET;
saddr.sin_port = htons(22222);
//Connect the 50 sockets 2000 times
for(int j = 0; j < 2000; ++j)
{
//Create the 50 sockets
for(i = 0; i < socks.size(); ++i)
{
socks[i] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socks[i] == INVALID_SOCKET)
std::cout << "Bad init\n";
}
//Connect and receive data on each of the sockets
for(i = 0; i < socks.size(); ++i)
{
if(socks[i] == INVALID_SOCKET)
{
std::cout << "Invalid socket\n";
continue;
}
if(::connect(socks[i], (SOCKADDR*)&saddr, sizeof(saddr)) == SOCKET_ERROR)
{
std::cout << "Err connect\n";
continue;
}
//Receive some data (don't bother checking for complete packet)
char buf[256];
int bytes = ::recv(socks[i], buf, 256, 0);
if(bytes == SOCKET_ERROR || bytes == 0)
{
std::cout << "Err recv\n";
continue;
}
//Stick a null on the end and print the message
buf[bytes] = '\0';
std::cout << buf << std::endl;
}
//Close the 50 sockets
for(i = 0; i < socks.size(); ++i)
{
int res = ::closesocket(socks[i]);
if(res == SOCKET_ERROR)
std::cout << "Bad close";
}
}