Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent network ports being left open on program crash

I took Computer Networking last semester and did some C programming in linux (using gcc) for my projects. One extremely tedious thing I kept running into was if my program crashed or stalled (which I then would have to hit Ctrl+C to kill it), the network port would still be left open for a minute or so. So if I wanted to immediately run the program again, I would have to first go into the header file, change the port, remake the program, and then finally run it. Obviously, this gets very tedious very fast.

Is there any way to configure it where the port is immediately released as soon as the process is killed? Either via some setting in linux, or in the makefile for my program, or even programmatically in C?

Edit: I'm referring to when writing a server and choosing a specific port to host the program.

like image 963
JoeCool Avatar asked Dec 10 '22 20:12

JoeCool


2 Answers

Set the the option SO_REUSEADDR on the socket.

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

From Beej's Guide to Network Programming.

like image 67
Cogsy Avatar answered Jan 22 '23 16:01

Cogsy


I bet it's about two minutes :) As @Cogsy noted, the SO_REUSEADDR socket option is your friend. Make yourself familiar with TCP states, it's TIME_WAIT state that causes you problems:

like image 29
Nikolai Fetissov Avatar answered Jan 22 '23 16:01

Nikolai Fetissov