麻烦帮我在centos环境下,用c++编程一个简单的防火墙程序
时间: 2024-03-01 08:54:15 浏览: 14
好的,下面是一个简单的防火墙程序的示例代码,仅供参考:
```c++
#include <iostream>
#include <cstring>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
const char* ALLOWED_IP = "127.0.0.1"; // 允许访问的IP地址
const int ALLOWED_PORT = 8888; // 允许访问的端口号
bool check_ip(const char* ip) {
// 检查IP地址是否合法
struct sockaddr_in sa;
int result = inet_pton(AF_INET, ip, &(sa.sin_addr));
return result != 0;
}
bool check_port(int port) {
// 检查端口号是否合法
return (port > 0 && port < 65536);
}
bool check_packet(const char* ip, int port) {
// 检查数据包是否合法
if (strcmp(ip, ALLOWED_IP) != 0 || port != ALLOWED_PORT) {
return false;
}
return true;
}
int main() {
int sockfd;
struct sockaddr_in addr;
char buf[1024];
// 创建socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("socket");
exit(1);
}
// 绑定IP和端口号
addr.sin_family = AF_INET;
addr.sin_port = htons(ALLOWED_PORT);
addr.sin_addr.s_addr = inet_addr(ALLOWED_IP);
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
perror("bind");
exit(1);
}
// 接收数据包并检查
while (true) {
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int n = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&client_addr, &len);
if (n < 0) {
perror("recvfrom");
continue;
}
buf[n] = '\0';
cout << "Received packet from " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << endl;
if (!check_ip(inet_ntoa(client_addr.sin_addr)) || !check_port(ntohs(client_addr.sin_port)) || !check_packet(inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port))) {
cout << "Packet dropped!" << endl;
continue;
}
cout << "Packet allowed!" << endl;
// 处理合法数据包
// ...
}
close(sockfd);
return 0;
}
```
这个程序使用UDP协议监听指定的IP地址和端口号,然后接收数据包并检查是否合法。如果不合法则丢弃,否则进行处理。在这个示例中,只有来源IP地址和端口号是指定的值时,才认为数据包是合法的。实际应用中,可能会有更复杂的规则和状态管理。