views:

510

answers:

3

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.

+10  A: 

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.

Cogsy
That's a good idea. Another alternative is, code your program for accepting the port number as input to avoid a recompile. To actually release the port like you want, you need to write a Ctrl-C handler and code the close there.
nik
(Unrelated) What was somebody thinking to make that fourth argument a pointer to an int instead of an int?
Kai
That's true, the above solution does not actually release the socket, but it does allow it to be re-bound on the next execution.
Cogsy
@Kai: (get|set)sockopt support all sorts of options on all sorts of sockets. Some values for the 2nd and 3rd argument result in the 4th argument being treated as a pointer to a structure or a string.
ephemient
It's ok if it doesn't technically release the socket, as long as the port can be reused, because that still solves my problem. Thanks!
JoeCool
+1  A: 

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.

Metiu
Yes, I'm referring to when writing a server, thanks.
JoeCool
+2  A: 

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:

 
Nikolai N Fetissov
Aww, I would have been much happier with a copy of the amazing ASCII diagram from page 23 of RFC 793 instead.
ephemient
Oh, yeh! I totally forgot about wonderful art of ASCII pictures :)
Nikolai N Fetissov