To properly close a socket in C++, you need to follow these steps:
Use the
close()
function to close the socket. Pass the socket descriptor as the argument.TEXT/X-C++SRC1close(sockfd);
Handle any necessary error checking after closing the socket.
TEXT/X-C++SRC1if (close(sockfd) == -1) { 2 std::cout << "Error closing socket" << std::endl; 3 return 1; 4}
Closing a socket is important to free up system resources and maintain proper network communication. Failure to close a socket can lead to resource leaks and potentially impact the network performance.
Here's an example code that demonstrates how to properly close a socket in C++:
TEXT/X-C++SRC
1#include <iostream>
2#include <sys/socket.h>
3
4int main() {
5 // Create a socket
6 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
7 if (sockfd == -1) {
8 std::cout << "Failed to create socket" << std::endl;
9 return 1;
10 }
11
12 // ... Set up server address and connect to server ...
13
14 // Close the socket
15 if (close(sockfd) == -1) {
16 std::cout << "Error closing socket" << std::endl;
17 return 1;
18 }
19
20 return 0;
21}
xxxxxxxxxx
18
int main() {
// Create a socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
std::cout << "Failed to create socket" << std::endl;
return 1;
}
// ... Set up server address and connect to server ...
// Close the socket
close(sockfd);
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment