Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I want to capture the packets from a particular port using RAW_SOCKETS so i wrote the following program but i am not getting any output .
Please help.


#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define BUFLEN 512
#define NPACK 10
#define PORT 9930

void diep(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in si_me, si_other;
    int s, i, slen=sizeof(si_other);
    char buf[BUFLEN];

    if ((s=socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL))==-1)
        diep("socket");

    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = PF_PACKET;
    si_me.sin_port = htons(PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(s, &si_me, sizeof(si_me))==-1)
        diep("bind");

    for (i=0; i<NPACK; i++) {
        if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
            diep("recvfrom()");
        printf("Received packet from %s:%d\nData: %s\n\n", 
                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
    }

    close(s);
    return 0;
}
Posted
Comments
Richard MacCutchan 2-Dec-13 6:06am    
Use your debugger to find out what is happening, and check that the other end is sending messages.
Robert Clove 2-Dec-13 6:25am    
ya other end is sending messages i saw it through tcpdump
Richard MacCutchan 2-Dec-13 6:31am    
Then I can only assume that there is something wrong with your receiever, so you need to work with your debugger to discover why.
JMH_FR 6-Dec-13 9:29am    
Did you tried with SOCK_RAW instead of SOCK_DGRAM ? And did you check you have CAP_NET_RAW capacity (if you are not running your prog as root ) ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900