Not an expert, but if you're using Modbus RTU over TCP then the MBAP header has the length of the Modbus message in it, so you conceptually do: receive(socket, &mbap_header, sizeof(mbap_header)); receive(socket, buffer, mbap_header.message_size);