92 lines
2.4 KiB
C
92 lines
2.4 KiB
C
/**
|
|
* 该文件用于匹配fw.html
|
|
* 使用该.c文件可实现从名为router的数据库中
|
|
* 实现获取前端页面输入的ip地址
|
|
* 对存有黑名单数据的ip_fw表进行写入或删除操作
|
|
*/
|
|
|
|
#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", "flykhan", "1202", "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;
|
|
}
|