Satyam Kumar - Lab Activity2 (2021btech106)
Satyam Kumar - Lab Activity2 (2021btech106)
SUBMITTED BY:
FACULTY GUIDE:
Dr. Devika Kataria
January 2024
Write the C language code for packet sniffer made using raw socket which used the
packets from Promiscuous mode of os and stores in a buffer. Apply filter for packet types
"TCP", "UDP" and "DNS" and show the port of entry and lenght of packets as well.
1.TCP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <net/if.h>
int main() {
int raw_socket, data_size;
char interface_name[IFNAMSIZ];
unsigned char *buffer = (unsigned char *)malloc(65536);
if (raw_socket == -1) {
perror("Socket creation error");
exit(EXIT_FAILURE);
}
while (1) {
data_size = recvfrom(raw_socket, buffer, 65536, 0, NULL, NULL);
if (data_size < 0) {
perror("Packet receive error");
exit(EXIT_FAILURE);
}
process_packet(buffer, data_size);
}
close(raw_socket);
free(buffer);
return 0;
}
#define DNS_PORT 53
int main() {
int raw_socket, data_size;
char interface_name[IFNAMSIZ];
unsigned char *buffer = (unsigned char *)malloc(65536);
if (raw_socket == -1) {
perror("Socket creation error");
exit(EXIT_FAILURE);
}
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(raw_socket, SIOCSIFFLAGS, &ifr) < 0) {
perror("Error while setting interface to promiscuous mode");
exit(EXIT_FAILURE);
}
while (1) {
data_size = recvfrom(raw_socket, buffer, 65536, 0, NULL, NULL);
if (data_size < 0) {
perror("Packet receive error");
exit(EXIT_FAILURE);
}
process_packet(buffer, data_size);
}
close(raw_socket);
free(buffer);
return 0;
}
3.UDP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <sys/ioctl.h>
#include <net/if.h>
int main() {
int raw_socket, data_size;
char interface_name[IFNAMSIZ];
unsigned char *buffer = (unsigned char *)malloc(65536);
if (raw_socket == -1) {
perror("Socket creation error");
exit(EXIT_FAILURE);
}
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(raw_socket, SIOCSIFFLAGS, &ifr) < 0) {
perror("Error while setting interface to promiscuous mode");
exit(EXIT_FAILURE);
}
while (1) {
data_size = recvfrom(raw_socket, buffer, 65536, 0, NULL, NULL);
if (data_size < 0) {
perror("Packet receive error");
exit(EXIT_FAILURE);
}
process_packet(buffer, data_size);
}
close(raw_socket);
free(buffer);
return 0;
}