#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <net/ethernet.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#define BUFFER_SIZE 65536
void process_packet(unsigned char* buffer, int size, FILE* log_file) {
struct ethhdr* ethernet_header = (struct ethhdr*)buffer;
struct iphdr* ip_header = (struct iphdr*)(buffer + sizeof(struct ethhdr));
if (ip_header->protocol == IPPROTO_TCP) {
struct tcphdr* tcp_header = (struct tcphdr*)(buffer + sizeof(struct ethhdr) + sizeof(struct iphdr));
fprintf(log_file, "TCP Packet: %s:%d -> %s:%d\n", inet_ntoa(*(struct in_addr*)&ip_header->saddr),
ntohs(tcp_header->source), inet_ntoa(*(struct in_addr*)&ip_header->daddr),
ntohs(tcp_header->dest));
} else if (ip_header->protocol == IPPROTO_UDP) {
struct udphdr* udp_header = (struct udphdr*)(buffer + sizeof(struct ethhdr) + sizeof(struct iphdr));
fprintf(log_file, "UDP Packet: %s:%d -> %s:%d\n", inet_ntoa(*(struct in_addr*)&ip_header->saddr),
ntohs(udp_header->source), inet_ntoa(*(struct in_addr*)&ip_header->daddr),
ntohs(udp_header->dest));
}
}
int main() {
int raw_socket;
unsigned char* buffer = (unsigned char*)malloc(BUFFER_SIZE);
raw_socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (raw_socket < 0) {
perror("Failed to create socket");
return -1;
}
time_t current_time = time(NULL);
struct tm* time_info = localtime(¤t_time);
char filename[20];
strftime(filename, sizeof(filename), "%Y_%m_%d_%H_%M_%S.log", time_info);
FILE* log_file = fopen(filename, "a");
if (!log_file) {
perror("Failed to open log file");
return -1;
}
while (1) {
struct sockaddr sa;
int sa_len = sizeof(sa);
int data_size = recvfrom(raw_socket, buffer, BUFFER_SIZE, 0, &sa, (socklen_t*)&sa_len);
if (data_size < 0) {
perror("Failed to receive");
return -1;
}
process_packet(buffer, data_size, log_file);
}
fclose(log_file);
free(buffer);
close(raw_socket);
return 0;
}