代码实现:其实他和tcp的传输方式是差不多的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
//定义缓存区大小
#define BUFFER_SIZE 1024
int main() {
//1.创建套接字
int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket == -1) {
perror("socket");
exit(1);
}
//设置地址
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("172.20.1.131");
server_addr.sin_port = htons(503);
//2.建立链接
if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
// 构建 Modbus TCP 读取保持寄存器请求报文
unsigned char request[12] = {
0x00, 0x00, // 事务标识符
0x00, 0x00, // 协议标识符
0x00, 0x06, // 长度
0x02, // 单元标识符
0x03, // 功能码:读取保持寄存器
0x00, 0x68, // 起始寄存器地址
0x00, 0x02 // 要读取的寄存器数量
};
//3.发送请求报文
if (write(client_socket, request, sizeof(request)) == -1) {
perror("write");
exit(1);
}
//4.接收响应报文
unsigned char response[BUFFER_SIZE];
int response_length = read(client_socket, response, BUFFER_SIZE);
if (response_length == -1) {
perror("read");
exit(1);
}
// 解析响应报文
if (response[7] != 0x03) {
printf("功能码错误\n");
exit(1);
}
//打印出对应寄存器的值
for(int i = 0; i<response_length;i++)
{
printf("0x%.2x ",response[i]);
}
printf("\n");
//测试
for(int i = 0; i<response_length;i++)
{
printf("0x%d ",response[i]);
}
printf("\n");
//拿到寄存器的实际数量(第9个位置是字节数,一个寄存器2字节)
int Reg_len = response[8]/2;
printf("读取到的数据是:\n");
for(int i=0;i<Reg_len;i++)
{
uint32_t reg_val = (response[9+i*2]) << 8 | (response[10+i*2]);
printf("保持寄存器%d的值:%d\n",i,reg_val);
}
close(client_socket);
return 0;
}