// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BUF_SIZE 1024

int main()
{
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        printf("Failed to create socket\n");
        return 1;
    }

    // bind socket
    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(1234);
    if (bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
    {
        printf("Failed to bind socket\n");
        close(sock);
        return 1;
    }

    printf("Listening to data on 0.0.0.0:1234\n");

    // receive UDP 数据包 and send msg
    char buf[BUF_SIZE] = { 0 };
    struct sockaddr_in client_addr;
    socklen_t len = sizeof(client_addr);
    while (true)
    {
        int n = recvfrom(sock, buf, BUF_SIZE - 1, 0, (struct sockaddr*)&client_addr, &len);

        if (n < 0)
        {
            printf("Failed to receive data\n");
            continue;
        }
        printf("Message content: %s\n", buf);
        if (buf[0] == 'q')
        {
            printf("Exiting...\n");
            break;
        }

        buf[n] = '\0';

        //用cjson解析json字符串
        cJSON* root = cJSON_Parse(buf);
        if (root != NULL)
        {
            // 判断 JSON 是否包含命令字段
            cJSON* cmd = cJSON_GetObjectItem(root, "cmd");
            if (cmd != NULL && cmd->valuestring != NULL)
            {
                // 如果命令为 "reboot",则执行系统重启
                if (strcmp(cmd->valuestring, "reboot") == 0)
                {
                    printf("Received reboot command, rebooting ...\n");
                    system("reboot");
                }
            }

            cJSON_Delete(root);  // 释放 cJSON 节点
        }

        char ip[INET_ADDRSTRLEN];
        memset(ip, 0, sizeof(ip));
        inet_ntop(AF_INET, &(client_addr.sin_addr), ip, INET_ADDRSTRLEN);
        printf("Server listening on [%s:%d]\n", ip, ntohs(server_addr.sin_port));

        const char* reply = "Hello from server!";
        if (sendto(sock, reply, strlen(reply), 0, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
        {
            printf("Failed to send reply\n");
            continue;
        }
    }

    // cleanup source
    close(sock);
    return 0;
}

GitHub 加速计划 / cj / cJSON
13
4
下载
Ultralightweight JSON parser in ANSI C
最近提交(Master分支:18 天前 )
c859b25d 17 天前
74e1ff49 this fixes CVE-2025-57052 21 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐