Search code examples
pythonudpscapy

cannot get dport from a UDP packet using python and scapy


despite having imported what I have found to be necessary, I cannot seem to get dport from an already-sniffed UDP packet.

    from scapy.layers import *
    from scapy.layers.inet import UDP, IP
    from scapy.sendrecv import send, sniff 

    packet = sniff(filter="UDP and src='127.0.0.1'", count=1)
    print(packet[UDP].dport)  

this code was supposed to print the destination port of a UDP packet I had sent myself. instead, an error occurred which reads "AttributeError: 'list' object has no attribute 'dport'" I have searched through countless documentation sites and have not found the error. thanks in advance.


Solution

  • sniff returns the list of packets it captured, even if you stop after one packet captured (with count=1). So just replace:

    print(packet[UDP].dport)
    

    with:

    print(packet[0][UDP].dport)
    

    And this should work.