写一个端口扫描的c语言程序
时间: 2023-06-08 12:06:57 浏览: 244
好的,以下是一个简单的端口扫描的C语言程序,它可以扫描目标主机的特定端口是否开放:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_PORTS 1000
int main(int argc, char *argv[]) {
int sockfd, ret, start, end, i, j;
struct sockaddr_in target_addr;
char *target_ip, port_status[MAX_PORTS];
if (argc != 4) {
printf("Usage: %s <target IP> <start port> <end port>\n", argv[0]);
exit(EXIT_FAILURE);
}
target_ip = argv[1];
start = atoi(argv[2]);
end = atoi(argv[3]);
if (start < 1 || end < 1 || start > MAX_PORTS || end > MAX_PORTS) {
printf("Invalid port range\n");
exit(EXIT_FAILURE);
}
if (start > end) {
printf("Invalid port range: start port must be less than or equal to end port\n");
exit(EXIT_FAILURE);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("Failed to create socket: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
memset(&target_addr, 0, sizeof(target_addr));
target_addr.sin_family = AF_INET;
target_addr.sin_addr.s_addr = inet_addr(target_ip);
// Scan ports
for (i = start; i <= end; i++) {
target_addr.sin_port = htons(i);
ret = connect(sockfd, (struct sockaddr *)&target_addr, sizeof(target_addr));
if (ret == 0) {
printf("Port %d is open\n", i);
port_status[i] = 1;
} else {
port_status[i] = 0;
}
}
printf("Port scan completed. Open ports: ");
for (j = start; j <= end; j++) {
if (port_status[j] == 1) {
printf("%d ", j);
}
}
printf("\n");
close(sockfd);
return 0;
}
```
请注意,这个程序需要在Linux或Unix系统上运行,因为它使用了Unix网络编程API。如果需要在Windows上运行,请使用Winsock API。
阅读全文