Why cannot I bind a socket?

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.