Original Post
I wrote my server in C++ and put it on am amazon ec2-micro instance, listening for connections on port 1234. Tested it over period of weeks with no issues. I left it running indefinitely for several months and after some period of time (unknown) discovered it was no longer running. I logged in and tried to restart and got the "address already in use" error when attempting to bind the listensocket to port 1234. Note that SO_REUSEADDR was already set. Over a period of several days I continued to try and it has never been released. I suppose this amazon instance is set with TIME_WAIT=infinity so it will wait until server reboots, but I am afraid to reboot it due to posts like this: http://blog.9minutes...ot-t1micro-ec2/
I have discovered that whenever I kill the server process when it is currently connected to a client, this error will occur when I try to restart the server..so I need to change the port that it waits on to get it back up. But thats not viable solution, because clients need to hardcode the port to connect to. What do I do?
I have discovered that whenever I kill the server process when it is currently connected to a client, this error will occur when I try to restart the server..so I need to change the port that it waits on to get it back up. But thats not viable solution, because clients need to hardcode the port to connect to. What do I do?
bool resume_listening()
{
std::cout << "Listening for new connections..\n";
if ( ::listen( listenSocket, SOMAXCONN ) == SOCKET_ERROR )
{
perror("listen listenSocket");
std::cout << "Error listening on socket\n";
closesocket(listenSocket);
return false;
}
return true;
}
bool create_listen_socket(int port)
{
std::cout << "Creating listener socket..\n";
//create listen socket
listenSocket = socket( AF_INET, SOCK_STREAM, 0 );
if (listenSocket == INVALID_SOCKET) {
perror("create listenSocket");
std::cout << "Unable to create listenSocket\n";
return false;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the client to be connected to.
struct sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(port);
// Enable address reuse
//discussion: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html
int on = 1;
setsockopt( listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on) );
//setup
if ( bind(listenSocket, (SOCKADDR*)&service, sizeof(service) ) == SOCKET_ERROR )
{
perror("bind listenSocket");
std::cout << "Unable to bind listenSocket\n";
closesocket(listenSocket);
return false;
}
return resume_listening();
}