上传实现防火墙添加删除代码

This commit is contained in:
wang_chengh 2023-09-22 09:36:42 +08:00
parent afc1b2e97e
commit a6a46d9b19
1 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,84 @@
#include <cjson/cJSON.h>
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}