Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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:

 

I assume the program you're writing is a server, so you need to use a known port. If that's the case, you should use the SO_REUSE_ADDR option on the socket as pointed out by Cogsy.

If on the other hand you're writing a client sw, then you should avoid choosing a particular port, allowing the system to hand you a random one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top