'How to close tcp server socket correctly

can anyone explain me, what I am doing wrong with my tcp server termination?

In my program (single instance), I started another program which starts a tcp server. For the tcp server it is only allowed to listen to one connection.

After a connection was established between client and my server, a few messages are shared. As soon as the message protocoI has passed through, I want to terminate the server socket, reset my internal states and close my sub-programm.

After a few seconds, it will be possible to open my sub-programm again. If so, I open the socket again... The same network device, the same ip address and the same port as before will be used...

My problem: my sub-programm crashes when running the 2nd time.

With netstat I analyzed my socket and found out, it stays in state LAST_ACK. This can take more than 60 seconds (timeout?) till the socket is finally closed.

For closing the socket, I used the following code:

if (0 != shutdown(socketDescriptor_, SHUT_RDWR)) {
    std::cout << "Read/write of socket deactivated" << std::endl;
}
if (0 == close(socketDescriptor_)) {
    std::cout << "Socket is destroyed" << std::endl;
    socketDescriptor_ = -1;
}

Any ideas? Thanks for your help!

Kind regards, Matthias



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source