Home >Backend Development >C++ >How do C++ functions establish and manage client sockets in network programming?
To establish and manage client sockets in C, you need to follow the following steps: Use the socket() function to create a socket. Use the connect() function to connect the socket to the server. Use the send() and recv() functions to exchange data with the server.
C function creates and manages client sockets in network programming
Establishes and manages client sockets is a basic task in network programming, and C provides several functions to achieve this goal.
Establish a client socket
Use the socket()
function to create a socket:
#include <sys/socket.h> int socket(int domain, int type, int protocol);
AF_INET
(IPv4) or AF_INET6
(IPv6). SOCK_STREAM
(TCP) or SOCK_DGRAM
(UDP). 0
, allowing the operating system to choose the default protocol. Example:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
Connect to the server
Use the connect()
function Connect client socket to server:
#include <sys/socket.h> int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
sockaddr_in
). Example:
struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); inet_pton(AF_INET, "192.168.1.100", &servaddr.sin_addr); int rc = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
Send and receive data
Use send()
and recv()
functions exchange data with the server:
#include <sys/socket.h> ssize_t send(int sockfd, const void *buf, size_t len, int flags); ssize_t recv(int sockfd, void *buf, size_t len, int flags);
0
. Example:
char buf[1024]; int n = recv(sockfd, buf, sizeof(buf), 0);
Practical case: Establishing and managing client sockets
This is a A complete C program demonstrating how to use the above functions to establish and manage client sockets:
#include <iostream> #include <sys/socket.h> #include <netinet/in.h> int main() { // 创建套接字 int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { std::cout << "Error creating socket" << std::endl; return -1; } // 连接到服务器 struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); inet_pton(AF_INET, "192.168.1.100", &servaddr.sin_addr); int rc = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if (rc < 0) { std::cout << "Error connecting to server" << std::endl; return -1; } // 发送数据 const char *msg = "Hello, server!"; int n = send(sockfd, msg, strlen(msg), 0); if (n < 0) { std::cout << "Error sending data" << std::endl; return -1; } // 接收数据 char buf[1024]; n = recv(sockfd, buf, sizeof(buf), 0); if (n < 0) { std::cout << "Error receiving data" << std::endl; return -1; } std::cout << "Received data: " << buf << std::endl; // 关闭套接字 close(sockfd); return 0; }
The above is the detailed content of How do C++ functions establish and manage client sockets in network programming?. For more information, please follow other related articles on the PHP Chinese website!