写一段监控高危端口的代码
时间: 2023-04-04 13:05:10 浏览: 108
以下是一段监控高危端口的代码,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 22 // 监控的端口号
int main() {
int sockfd;
struct sockaddr_in addr;
// 创建 socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
// 设置地址
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(PORT);
// 绑定地址
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
// 监听端口
if (listen(sockfd, 10) < 0) {
perror("listen");
exit(1);
}
// 接受连接
while (1) {
int connfd;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
connfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
if (connfd < 0) {
perror("accept");
continue;
}
// 判断连接的端口是否为高危端口
if (client_addr.sin_port == htons(PORT)) {
printf("High-risk port detected! IP: %s\n", inet_ntoa(client_addr.sin_addr));
}
close(connfd);
}
close(sockfd);
return 0;
}
阅读全文