生成一段跨设备的TCP 通信的Linux C代码,设备1为客户端,ip是:192.168.52.65,设备2为服务器端,ip是:192.168.52.66
时间: 2024-11-25 16:15:56 浏览: 6
在Linux环境下编写C语言代码来实现在两个设备间的TCP通信,通常会涉及socket编程。下面是一个简单的示例,展示了如何创建一个客户端连接到指定IP地址的服务器:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
#define SERVER_IP "192.168.52.66"
#define CLIENT_IP "192.168.52.65"
int main() {
int client_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t addr_len = sizeof(server_addr);
char send_msg[] = "Hello from Client!";
char receive_msg[1024] = "";
// 创建客户端套接字
if ((client_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Error creating client socket");
return 1;
}
// 设置客户端地址信息
memset(&client_addr, 0, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_port = htons(PORT);
inet_aton(CLIENT_IP, &client_addr.sin_addr);
// 连接到服务器
if (connect(client_sock, (struct sockaddr *)&client_addr, addr_len) < 0) {
perror("Error connecting to server");
close(client_sock);
return 1;
}
printf("Connected to server at %s:%d\n", SERVER_IP, PORT);
// 发送消息
if (send(client_sock, send_msg, strlen(send_msg), 0) <= 0) {
perror("Error sending message");
close(client_sock);
return 1;
}
printf("Message sent: %s\n", send_msg);
// 接收服务器的消息
ssize_t bytes_received = recv(client_sock, receive_msg, sizeof(receive_msg), 0);
if (bytes_received > 0) {
receive_msg[bytes_received] = '\0'; // NULL terminate the string
printf("Received message: %s\n", receive_msg);
} else if (bytes_received == 0) {
printf("Server closed the connection.\n");
} else {
perror("Error receiving message");
}
// 关闭套接字
close(client_sock);
return 0;
}
```
这个示例演示了基本的客户端功能,实际应用中可能需要处理错误情况,并在服务器响应后断开连接。请确保设备1(运行此程序的计算机)和设备2都已开启了监听该端口的服务。
阅读全文