我试图用lwip netconn API(使用esp open rtos)为ESP8266编写简单的SNTP客户端。问题是我无法从服务器接收答案。
代码(没有错误检查和调试消息):

#include <string.h>

#include <lwip/api.h>
#include <lwip/err.h>

struct sntp_message
{
    u8_t li : 2;
    u8_t vn : 3;
    u8_t mode : 3;
    u8_t stratum;
    u8_t poll;
    u8_t precision;
    u32_t root_delay;
    u32_t root_dispersion;
    u32_t reference_identifier;
    u32_t reference_timestamp[2];
    u32_t originate_timestamp[2];
    u32_t receive_timestamp[2];
    u32_t transmit_timestamp[2];
} __attribute__((packed));

#define SNTP_MSG_LEN (sizeof(struct sntp_message))

int16_t sntp_sync(char* server)
{
    err_t err;
    int16_t result = ERR_OK;
    ip_addr_t sntp_server_address;
    struct netconn* connection = NULL;
    struct netbuf* send_buffer = NULL;
    struct netbuf* receive_buffer = NULL;
    struct sntp_message* send_buffer_data = NULL;

    err = netconn_gethostbyname(server, &sntp_server_address);
    connection = netconn_new(NETCONN_UDP);
    err = netconn_connect(connection, &sntp_server_address, 123);
    send_buffer = netbuf_new();
    send_buffer_data = netbuf_alloc(send_buffer, SNTP_MSG_LEN);
    memset(send_buffer_data, 0, SNTP_MSG_LEN);
    send_buffer_data->vn = 4;
    send_buffer_data->mode = 3; // Mode client.
    err = netconn_send(connection, send_buffer);
    err = netconn_recv(connection, &receive_buffer); // Here netconn_recv block my thread, and no data received. If i set timeout, i have timeout error.
    return result;
}

我的代码有什么问题?在接收数据(通过netconn_bind)之前,是否需要绑定连接?或者我忘了什么?

最佳答案

不要发明自行车。Simon Goldschmidt已经为LwIP编写了SNTP。Link。在这里您可以找到lwip-contrib描述和git repo。您还可以在github或任何地方查找镜像(可能已升级)。

关于c - lwip netconn api-无法从SNTP服务器接收答案,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39064017/

10-13 05:27