Q: I always fail to bind a socket. I can bind a socket only when I start the program for the first time, and then I will not be able to connect to this port when I use another program, however, I can scan this port using the port scanning software. What is the reason? How can this problem be solved? Thank you.
A: 1. Check whether the socket is properly closed.
2. if a socket is bound to a port, the socket is normally closed or the program exits, and the port remains bound for a period of time, other programs (or the original program that is restarted) the port cannot be bound. This problem can be avoided by calling the setsockopt statement after obtaining the socket descriptor:
Int sockfd;
Int opt = 1;
Int len = sizeof (opt );
Sockfd = socket (AF_INET, SOCK_STREAM, 0 );
Setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, & opt, & len );
Q: The cause is found out. It has nothing to do with the creation of the socket. It is mainly because the socket is not properly closed. In fact, it is not properly closed because static variables are used, there is no problem after it is changed. I think the general reason is that static variables are used in the Service.
From cwj649956781