c语言 socket TCP
时间: 2023-08-15 12:54:43 浏览: 79
C# socket tcp
4星 · 用户满意度95%
C语言中如何使用socket进行TCP通信呢?
在C语言中,可以使用socket库来创建TCP套接字并进行网络通信。下面是一个简单的示例代码,用于创建一个TCP服务器和一个TCP客户端。
TCP服务器端示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
// 创建套接字
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8080);
// 将套接字绑定到指定地址和端口
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_socket, 5) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
// 等待客户端连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
// 接收和发送数据
char buffer[1024];
ssize_t num_bytes;
while ((num_bytes = recv(client_socket, buffer, sizeof(buffer), 0)) > 0) {
buffer[num_bytes] = '\0';
printf("Received: %s\n", buffer);
if (send(client_socket, buffer, num_bytes, 0) == -1) {
perror("send");
exit(EXIT_FAILURE);
}
}
// 关闭连接
close(client_socket);
close(server_socket);
return 0;
}
```
TCP客户端端示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
// 创建套接字
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("服务器IP地址");
server_addr.sin_port = htons(8080);
// 连接服务器
if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
// 发送和接收数据
char message[] = "Hello, server!";
if (send(client_socket, message, sizeof(message), 0) == -1) {
perror("send");
exit(EXIT_FAILURE);
}
char buffer[1024];
ssize_t num_bytes = recv(client_socket, buffer, sizeof(buffer), 0);
if (num_bytes == -1) {
perror("recv");
exit(EXIT_FAILURE);
}
buffer[num_bytes] = '\0';
printf("Received: %s\n", buffer);
// 关闭连接
close(client_socket);
return 0;
}
```
在示例代码中,服务器端创建一个套接字、绑定到指定地址和端口、监听连接请求、接受客户端连接、接收客户端发送的数据并回复,最后关闭连接。客户端创建一个套接字、连接到服务器、发送数据、接收服务器回复,最后关闭连接。
请注意,示例代码中的IP地址和端口号需要根据实际情况进行修改。
阅读全文