diff --git a/www/cgi-bin/c_mysql_ip_fw_add_del.c b/www/cgi-bin/c_mysql_ip_fw_add_del.c new file mode 100644 index 0000000..f7ee6f1 --- /dev/null +++ b/www/cgi-bin/c_mysql_ip_fw_add_del.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include + +int main() { + MYSQL *conn; + MYSQL_RES *res; + MYSQL_ROW row; + + conn = mysql_init(NULL); + if (conn == NULL) { + fprintf(stderr, "mysql_init() failed\n"); + exit(1); + } + + if (mysql_real_connect(conn, "localhost", "root", "root", "router", 3306, + NULL, 0) == NULL) { + fprintf(stderr, "mysql_real_connect() failed\n"); + mysql_close(conn); + exit(1); + } + + // 获取前端传递的JSON数据 + char request_data[128] = ""; + fgets(request_data, 128, stdin); + + // 解析JSON数据 + cJSON *p = cJSON_Parse(request_data); + cJSON *code = cJSON_GetObjectItemCaseSensitive(p, "code"); + cJSON *ip = cJSON_GetObjectItemCaseSensitive(p, "ip"); + + if (!cJSON_IsNumber(code) || !cJSON_IsString(ip)) { + fprintf(stderr, "Error getting code or IP address from JSON data\n"); + cJSON_Delete(p); + mysql_close(conn); + exit(1); + } + + int operation_code = code->valueint; + char *ip_address = ip->valuestring; + + if (operation_code == 0) { + // 插入IP地址到数据库 + char query[1000]; + sprintf(query, "INSERT INTO ip_fw (ip) VALUES ('%s')", ip_address); + + if (mysql_query(conn, query)) { + fprintf(stderr, "INSERT query failed. Error: %s\n", + mysql_error(conn)); + cJSON_Delete(p); + mysql_close(conn); + exit(1); + } + } else if (operation_code == 1) { + // 从数据库中删除指定IP地址 + char query[1000]; + sprintf(query, "DELETE FROM ip_fw WHERE ip='%s'", ip_address); + + if (mysql_query(conn, query)) { + fprintf(stderr, "DELETE query failed. Error: %s\n", + mysql_error(conn)); + cJSON_Delete(p); + mysql_close(conn); + exit(1); + } + } else { + fprintf(stderr, "Invalid operation code\n"); + cJSON_Delete(p); + mysql_close(conn); + exit(1); + } + + cJSON_Delete(p); + + printf("Content-Type: application/json;charset=utf-8\r\n"); + printf("\r\n"); + printf("{\"status\": \"success\"}"); + + mysql_close(conn); + + return 0; +}