How to prevent network ports remaining open when a program crashes

Last semester, I took Computer Networking and did some Linux C-programming (using gcc) for my projects. One very tedious thing that I came across was that if my program crashed or died out (I would then have to press Ctrl + C to kill it), the network port would still remain open for a minute or so. Therefore, if I want to run the program again, I will have to first go to the header file, change the port, redo the program and then run it. Obviously, this is very tiring very fast.

Is there a way to configure it when the port is immediately freed as soon as the process is killed? Either through some tweaking in linux, or in the makefile for my program, or even programmatically in C?

Edit: I mean when writing a server and choosing a specific port for hosting the program.

+4
source share
3 answers

Set the SO_REUSEADDR option on the socket.

 int yes = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); 

From Bej Network Programming Guide .

+11
source

I bet for two minutes :) As @Cogsy noted, the socket option SO_REUSEADDR is your friend. Become familiar with TCP states, this TIME_WAIT state causes problems:

+2
source

I assume that the program you are writing is a server, so you need to use a well-known port. If so, you should use the SO_REUSE_ADDR option on the socket, as indicated by Cogsy.

If, on the other hand, you write the sw client, then you should avoid choosing a specific port, allowing the system to give you a random option.

+1
source

Source: https://habr.com/ru/post/1286371/


All Articles