Created
March 6, 2012 12:21
-
-
Save khayrov/1985957 to your computer and use it in GitHub Desktop.
Packet capture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <sys/ioctl.h> | |
#include <net/if.h> | |
#include <netinet/in.h> | |
#include <netpacket/packet.h> | |
#include <net/ethernet.h> | |
int main(int argc, char **argv) | |
{ | |
int sockfd; | |
struct ifreq if_info; | |
int ifindex; | |
struct sockaddr_ll lladdr = { 0 }; | |
int i; | |
char packetbuf[1500]; | |
memset(&if_info, 0, sizeof(if_info)); | |
if (argc < 2) | |
{ | |
fprintf(stderr, "Usage: %s if-name\n", argv[0]); | |
return 1; | |
} | |
sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); | |
if (sockfd < 0) | |
{ | |
perror("socket() failed"); | |
return 1; | |
} | |
strncpy(if_info.ifr_name, argv[1], IFNAMSIZ); | |
if (ioctl(sockfd, SIOCGIFINDEX, &if_info)) | |
{ | |
perror("ioctl(SIOCGIFINDEX) failed"); | |
close(sockfd); | |
return 1; | |
} | |
ifindex = if_info.ifr_ifindex; | |
printf("%s index = %d\n", if_info.ifr_name, ifindex); | |
lladdr.sll_family = AF_PACKET; | |
lladdr.sll_ifindex = ifindex; | |
if (bind(sockfd, (struct sockaddr*)&lladdr, sizeof(lladdr))) | |
{ | |
perror("bind() failed"); | |
close(sockfd); | |
return 0; | |
} | |
for (i = 0; i < 10; ++i) | |
{ | |
ssize_t bytes_read = read(sockfd, packetbuf, sizeof(packetbuf)); | |
if (bytes_read < 0) | |
{ | |
perror("read() failed"); | |
break; | |
} | |
printf("Receieved packet len = %d\n", (int)bytes_read); | |
} | |
close(sockfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment