Amit Kumar
Amit Kumar

Reputation: 11

How to use the pcapy library in python to capture UDP packet by the method pcapy.next()

I am using cap.next() to capture UDP packets. Once it starts receiving packets it never comes out even if no packet is coming. Please help me. I have given the code below

If I would be using .loop attribute I could use

p = pcapy.open_live(dev, 65536, 1, 1)
p.setfilter('udp and src host 169.254.18.15 and port 5001')

print("capturing data...")
dumper = p.dump_open('data_loop.txt')

p.loop(NUM_OF_packet_to_receive, handle_packet)   

By the previous code I can apply filter and in the p.loop, I could specify the number of packets to be received.

But I have to use p.next() and apply filter and set timeout. Can anybody help me to apply filter and set timeout.

(pcapy doc is not properly written, any assists are welcome.) Right now, I filtering form the raw data by my own, not using pcapy filter.

Code:

import time
import socket
from struct import *
import datetime
import pcapy
import sys

def getInterface():
    ifs = pcapy.findalldevs()
    if len(ifs) == 0:
        print("you don't have enough permission to open any interface")
        sys.exit(1)
    elif len(ifs) == 1:
        print("only one interface present, defaulting to it")
        return ifs[0]
    count = 0
    for iface in ifs:
        print(count, ": ", iface)
        count += 1
    idx = int(input('Please select an interface: '))
    return ifs[idx]

dev = getInterface()
index = 0
cap = pcapy.open_live(dev,
                      65536,  # to ensure capturing all of the
                      1,  # promiscious mode on
                      0)  # time out
print("Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, cap.getnet(),
                                                         cap.getmask(),
                                                         cap.datalink()))
print("capturing data...")
dumper = cap.dump_open('data_p.txt')
while True:
    (header, packet) = cap.next()
    if ((len(packet) == 542) and
            (packet[26] == 169) and
            (packet[27] == 254) and
            (packet[29] == 15)):
        index += 1
        print(index)

Upvotes: 1

Views: 563

Answers (0)

Related Questions