C++ 如何关闭套接字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12006223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:45:17  来源:igfitidea点击:

How to close socket

c++sockets

提问by Avihai Marchiano

Run c++ on Ubuntu. I open socket in this way:

在 Ubuntu 上运行 C++。我以这种方式打开套接字:

socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW))

What do i need to do in the end of the use? Some socket will be used as long as the program run , do i need to check them from a while? to see if socket still exist?

使用结束后我需要做什么?只要程序运行,就会使用一些套接字,我需要暂时检查它们吗?看看socket是否还存在?

回答by Kerrek SB

The socket exists until you call closeon its file descriptor. Since you have a raw IP socket, there's no notion of "being alive". Just close it when you're done using it.

套接字一直存在,直到您调用close其文件描述符。由于您有一个原始 IP 套接字,因此没有“活着”的概念。用完后关闭即可。

回答by Kerrek SB

As its docs/man page say, socket() returns an open file descriptor or -1 if it fails. That means you have to close it as you would close any other file descriptor:

正如其文档/手册页所说,socket() 返回一个打开的文件描述符,如果失败则返回 -1。这意味着您必须像关闭任何其他文件描述符一样关闭它:

close(sockfd);