I am doing a sniffing of the network and trying to get ip address and port number on every tcp packet.
I used scapy with python and could successfully sniff packets and in a callback function could even print the packet summary. But I would want to do more, like fetching only the IP address of the source and its port number. How can i accomplish it? Below is my code:
#!/usr/bin/evn python
from scapy.all.import.*
def print_summary(pkt):
packet = pkt.summary()
print packet
sniff(filter="tcp",prn=packet_summary)
Please suggest a method to print only the source IP address of every packet.
Thanks.
Sniffing packets using scapy:To sniff the packets use the sniff() function. The sniff() function returns information about all the packets that has been sniffed. To see the summary of packet responses, use summary(). The sniff() function listens for an infinite period of time until the user interrupts.
The sr() function is for sending packets and receiving answers. The function returns a couple of packet and answers, and the unanswered packets. The function sr1() is a variant that only return one packet that answered the packet (or the packet set) sent. The packets must be layer 3 packets (IP, ARP, etc.).
The prn argument is defined as: prn: function to apply to each packet. If something is returned, it is displayed.
It is not very difficult. Try the following code:
#!/usr/bin/env python
from scapy.all import *
def print_summary(pkt):
if IP in pkt:
ip_src=pkt[IP].src
ip_dst=pkt[IP].dst
if TCP in pkt:
tcp_sport=pkt[TCP].sport
tcp_dport=pkt[TCP].dport
print " IP src " + str(ip_src) + " TCP sport " + str(tcp_sport)
print " IP dst " + str(ip_dst) + " TCP dport " + str(tcp_dport)
# you can filter with something like that
if ( ( pkt[IP].src == "192.168.0.1") or ( pkt[IP].dst == "192.168.0.1") ):
print("!")
sniff(filter="ip",prn=print_summary)
# or it possible to filter with filter parameter...!
sniff(filter="ip and host 192.168.0.1",prn=print_summary)
Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With