我们如何获取源IP地址和目标IP地址?

How can we Get the source and destination IP addresses?

我使用以下代码从 .pcap 文件中获取 information 关于 DNS 数据包:

import scapy.layers.dns
from scapy.all import *
dnsRecords = {}
def handlePkt(pkt):
    if pkt.haslayer(scapy.layers.dns.DNSRR):
        rrname = pkt.getlayer(scapy.layers.dns.DNSRR).rrname
        rdata = pkt.getlayer(scapy.layers.dns.DNSRR).rdata
        if dnsRecords.has_key(rrname):
            if rdata not in dnsRecords[rrname]:
                dnsRecords[rrname].append(rdata)
        else:
            dnsRecords[rrname] = []
            dnsRecords[rrname].append(rdata)
def main():
    pkts = rdpcap('dns.pcap')
    for pkt in pkts:
        handlePkt(pkt)
    for item in dnsRecords:
        print('[+] '+item+' has '+str(len(dnsRecords[item])) + ' unique IPs.')
if __name__ == '__main__':
  main()

结果:

你能告诉我,我怎样才能将目标IP地址和源IP地址添加到这个结果中,以便有以下类型的输出:

"ip_src": "192.168.1.1", "ip_dst": "192.168.1.2", "dns_": "google.com. has 1 unique IPs."

对于这个问题,我深表歉意,如果它看起来不正确,我对 scapy library 不是很了解。非常感谢!

我设法解决了这个问题,下面是我的代码:

#!/usr/bin/python3

import scapy.layers.dns
import scapy.layers.inet
from scapy.all import *
import json


def gettingDataFromDNSTraffic(pkt):
    json_file = "/tmp/receivedDNSProtocolData.json"
    data = []
    if pkt.haslayer(scapy.layers.dns.DNSQR):
        q_type = pkt.getlayer(scapy.layers.dns.DNSQR).qtype
        if q_type == 16:
            q_name = pkt.getlayer(scapy.layers.dns.DNSQR).qname
            q_name = q_name.decode("utf-8")
            ip_src_prt = None
            ip_dst_prt = None
            port_src_prt = None
            for ip_src in pkt:
                ip_src_prt = ip_src[scapy.layers.inet.IP].src
            for ip_dst in pkt:
                ip_dst_prt = ip_dst[scapy.layers.inet.IP].dst
            for port_src in pkt:
                port_src_prt = port_src[scapy.layers.inet.UDP].sport
            for port_dst in pkt:
                port_dst_prt = port_dst[scapy.layers.inet.UDP].dport

                data.append(
                    {'Incorrect_DNS_name': q_name[:-1], 'Source_IP': ip_src_prt, 'Source_Port': str(port_src_prt),
                     'Destination_IP': ip_dst_prt, 'Destination_Port': str(port_dst_prt)
                     })
                with open(json_file, "a") as file:
                    json.dump(data, file, indent=1)


def main():
    pkts = rdpcap('SRV_NC.pcap')
    for pkt in pkts:
        gettingDataFromDNSTraffic(pkt)
        
        
if __name__ == '__main__':
    main()

如果您觉得代码不正确,请原谅。

我把结果写在了一个JSON文件中:

突然间,有人会派上用场