如何防止网络端口在程序崩溃时保持打开状态

发布于 2024-07-24 13:59:06 字数 325 浏览 5 评论 0原文

我上学期学习了计算机网络,并在 Linux 中(使用 gcc)为我的项目做了一些 C 编程。 我经常遇到的一件极其乏味的事情是,如果我的程序崩溃或停止(然后我必须按 Ctrl+C 来终止它),网络端口仍会保持打开状态一分钟左右。 因此,如果我想立即再次运行该程序,我必须首先进入头文件,更改端口,重新制作程序,然后最后运行它。 显然,这很快就会变得非常乏味。

有没有办法配置成进程一被杀死就立即释放端口? 要么通过linux中的一些设置,要么在我的程序的makefile中,甚至以C语言编程?

编辑:我指的是编写服务器并选择特定端口来托管程序时。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

就像说晚安 2024-07-31 13:59:06

在套接字上设置选项SO_REUSEADDR

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

来自Beej 网络编程指南

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.

太阳哥哥 2024-07-31 13:59:06

我打赌大约两分钟:)
正如 @Cogsy 指出的,SO_REUSEADDR 套接字选项是您的朋友。
让自己熟悉 TCP 状态,TIME_WAIT 状态会给您带来问题:

 

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:

 

我假设您正在编写的程序是服务器,因此您需要使用已知的端口。 如果是这种情况,您应该在套接字上使用 SO_REUSE_ADDR 选项,如 Cogsy 所指出的。

另一方面,如果您正在编写客户端软件,那么您应该避免选择特定端口,从而允许系统为您提供一个随机端口。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文