LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Networking (https://www.linuxquestions.org/questions/linux-networking-3/)
-   -   packet raw socket - C sniffer (https://www.linuxquestions.org/questions/linux-networking-3/packet-raw-socket-c-sniffer-4175558275/)

elbarto333 11-07-2015 03:54 PM

packet raw socket - C sniffer
 
Hi guys... I make this program in C for sniffing my lan network. I use Raw Packet socket (AF_PACKET) why i need see the layer 2 info of each packet, but the variable "len" return only "-1". Why??? (I use "lo" interface for testing only). This is the code:

#include <stdio.h>
#include <sys/socket.h>
#include <net/ethernet.h>
#include <linux/if_packet.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>

main()
{
struct sockaddr_ll sll;
struct ifreq if_idx;

unsigned char *buffer;
int x, len;

int con = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));


memset(&if_idx, 0, sizeof(struct ifreq));
strncpy(if_idx.ifr_name, "lo", IFNAMSIZ-1);
ioctl(con, SIOCGIFINDEX, &if_idx);

memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_ifindex = if_idx.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);

bind(con, (const struct sockaddr *) &sll, sizeof(sll));

len = read(con, buffer, 4096);
printf("%i\n\n", len);
for (x = 0; x < len; x++)
{
printf("%x ", buffer[x]);
}
}


TANKS for all.

berndbausch 11-07-2015 08:05 PM

I am ignorant about socket, let alone raw socket programming, but are you sure the socket(), ioctl() and bind() system calls succeed? You never check.

In addition to checking the return value, also look at errno when an error condition is detected. Also for the read() call.

elbarto333 11-07-2015 11:58 PM

(SOLVED)

The problem was the not malloc for *buffer pointer, this does the read() error.

Regards.


All times are GMT -5. The time now is 11:33 PM.