
Analyzing Network Packets With Scapy
- 342 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Inspect and analyze network traffic with Scapy when you are validating APIs, debugging protocols, or reviewing security during ship and operate.
About
analyzing-network-packets-with-scapy is an agent skill from a cybersecurity skills bundle that guides solo builders through packet capture and analysis using Python’s Scapy library. Install it when you ship networked services—REST gateways, webhooks, agents calling third-party APIs—and need to confirm what actually crosses the wire instead of trusting application logs alone. The skill sits in the security lane of the journey: reproducing suspicious flows, validating TLS and protocol behavior, and supporting audit-style questions during ship and early operate. Prism’s excerpt emphasizes licensing and collection context; treat the skill as procedural knowledge for structured Scapy workflows rather than a hosted scanner. It suits intermediate builders comfortable running capture tooling locally or in lab environments. Use it alongside code review and monitoring skills when failures are intermittent or when you suspect misconfigured clients, DNS, or middleboxes.
- Scapy-oriented patterns for capturing and dissecting network packets
- Supports security review and incident-style protocol debugging
- Fits Apache 2.0 cybersecurity skills collection workflows
- Use when prompts need packet-level evidence, not only log lines
- Pairs with broader appsec and audit practices in agent-assisted reviews
Analyzing Network Packets With Scapy by the numbers
- 342 all-time installs (skills.sh)
- +18 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #593 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-network-packets-with-scapyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 342 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Inspect and analyze network traffic with Scapy when you are validating APIs, debugging protocols, or reviewing security during ship and operate.
Files
Analyzing Network Packets with Scapy
Overview
Scapy is a Python packet manipulation library that enables crafting, sending, sniffing, and dissecting network packets at granular protocol layers. This skill covers using Scapy for security-relevant tasks including TCP/UDP/ICMP packet crafting, pcap file analysis, protocol field extraction, SYN scan implementation, DNS query analysis, and detecting anomalous traffic patterns such as unusually fragmented packets or malformed headers.
When to Use
- When investigating security incidents that require analyzing network packets with scapy
- When building detection rules or threat hunting queries for this domain
- When SOC analysts need structured procedures for this analysis type
- When validating security monitoring coverage for related attack techniques
Prerequisites
- Python 3.8+ with
scapylibrary installed (pip install scapy) - Root/administrator privileges for raw socket operations (sniffing, sending)
- Npcap (Windows) or libpcap (Linux) for packet capture
- Authorization to perform packet operations on target network
Steps
1. Read and parse pcap/pcapng files with rdpcap() for offline analysis 2. Extract protocol layers (IP, TCP, UDP, DNS, HTTP) and field values 3. Compute traffic statistics: top talkers, protocol distribution, port frequency 4. Detect SYN flood patterns by analyzing TCP flag ratios 5. Identify DNS exfiltration indicators via query length and entropy analysis 6. Craft custom probe packets for authorized network testing 7. Export findings as structured JSON report
Expected Output
JSON report containing packet statistics, protocol distribution, top source/destination IPs, detected anomalies (SYN floods, DNS tunneling indicators, fragmentation attacks), and per-flow summaries.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Scapy Network Packet Analysis API Reference
Core Scapy Functions
Reading Packets
from scapy.all import rdpcap, sniff, wrpcap
# Read pcap file
packets = rdpcap("capture.pcap")
# Live sniff with BPF filter (requires root)
packets = sniff(filter="tcp port 80", count=100, iface="eth0")
# Write packets to pcap
wrpcap("output.pcap", packets)Packet Layer Access
from scapy.all import IP, TCP, UDP, DNS, DNSQR, ICMP
pkt = packets[0]
pkt.haslayer(IP) # Check if layer exists
pkt[IP].src # Source IP
pkt[IP].dst # Destination IP
pkt[TCP].sport # Source port
pkt[TCP].dport # Destination port
pkt[TCP].flags # TCP flags: S, SA, A, FA, R, PA
pkt[DNS].qd.qname # DNS query name
pkt[ICMP].type # ICMP type (8=echo request, 0=echo reply)Packet Crafting
from scapy.all import IP, TCP, sr1, send
# SYN probe (authorized testing only)
syn = IP(dst="192.168.1.1") / TCP(dport=80, flags="S")
response = sr1(syn, timeout=2, verbose=0)
# ICMP ping
ping = IP(dst="192.168.1.1") / ICMP()
send(ping, verbose=0)
# Custom DNS query
dns = IP(dst="8.8.8.8") / UDP(dport=53) / DNS(rd=1, qd=DNSQR(qname="example.com"))Protocol Fields Reference
TCP Flags
| Flag | Value | Meaning |
|---|---|---|
| S | 0x02 | SYN |
| SA | 0x12 | SYN-ACK |
| A | 0x10 | ACK |
| F | 0x01 | FIN |
| R | 0x04 | RST |
| P | 0x08 | PSH |
ICMP Types
| Type | Meaning |
|---|---|
| 0 | Echo Reply |
| 3 | Destination Unreachable |
| 8 | Echo Request |
| 11 | Time Exceeded |
BPF Filter Syntax
tcp port 443 # TCP traffic on port 443
host 10.0.0.1 # All traffic to/from IP
src net 192.168.0.0/24 # Source from subnet
udp and port 53 # DNS traffic
tcp[tcpflags] & tcp-syn != 0 # SYN packets onlyCLI Usage
# Analyze pcap file for anomalies
python agent.py --pcap capture.pcap --output report.json
# Custom thresholds
python agent.py --pcap traffic.pcapng --syn-threshold 50 --dns-length 30
# Port scan detection sensitivity
python agent.py --pcap scan.pcap --scan-threshold 10#!/usr/bin/env python3
"""Network packet analysis agent using Scapy for pcap parsing and anomaly detection."""
import json
import math
import argparse
from collections import defaultdict, Counter
from datetime import datetime
from scapy.all import rdpcap, IP, TCP, UDP, DNS, DNSQR, ICMP
def load_pcap(filepath):
"""Load packets from a pcap/pcapng file."""
packets = rdpcap(filepath)
print(f"[+] Loaded {len(packets)} packets from {filepath}")
return packets
def extract_packet_info(packets):
"""Extract structured info from each packet with IP layer."""
records = []
for pkt in packets:
if not pkt.haslayer(IP):
continue
info = {
"src_ip": pkt[IP].src,
"dst_ip": pkt[IP].dst,
"proto": pkt[IP].proto,
"ttl": pkt[IP].ttl,
"length": len(pkt),
"flags": str(pkt[IP].flags),
"timestamp": float(pkt.time),
}
if pkt.haslayer(TCP):
info["src_port"] = pkt[TCP].sport
info["dst_port"] = pkt[TCP].dport
info["tcp_flags"] = str(pkt[TCP].flags)
info["protocol"] = "TCP"
elif pkt.haslayer(UDP):
info["src_port"] = pkt[UDP].sport
info["dst_port"] = pkt[UDP].dport
info["protocol"] = "UDP"
elif pkt.haslayer(ICMP):
info["icmp_type"] = pkt[ICMP].type
info["icmp_code"] = pkt[ICMP].code
info["protocol"] = "ICMP"
else:
info["protocol"] = str(pkt[IP].proto)
if pkt.haslayer(DNS) and pkt.haslayer(DNSQR):
info["dns_query"] = pkt[DNSQR].qname.decode("utf-8", errors="ignore").rstrip(".")
info["dns_type"] = pkt[DNSQR].qtype
records.append(info)
return records
def compute_traffic_stats(records):
"""Compute overall traffic statistics."""
src_ips = Counter(r["src_ip"] for r in records)
dst_ips = Counter(r["dst_ip"] for r in records)
protocols = Counter(r["protocol"] for r in records)
dst_ports = Counter(r.get("dst_port", 0) for r in records if r.get("dst_port"))
total_bytes = sum(r["length"] for r in records)
return {
"total_packets": len(records),
"total_bytes": total_bytes,
"unique_src_ips": len(src_ips),
"unique_dst_ips": len(dst_ips),
"top_src_ips": src_ips.most_common(10),
"top_dst_ips": dst_ips.most_common(10),
"protocol_distribution": dict(protocols),
"top_dst_ports": dst_ports.most_common(10),
}
def detect_syn_flood(records, threshold=100):
"""Detect SYN flood by counting SYN-only packets per destination IP."""
syn_counts = defaultdict(int)
synack_counts = defaultdict(int)
for r in records:
if r.get("tcp_flags") == "S":
syn_counts[r["dst_ip"]] += 1
elif r.get("tcp_flags") == "SA":
synack_counts[r["dst_ip"]] += 1
alerts = []
for ip, count in syn_counts.items():
ack_count = synack_counts.get(ip, 0)
ratio = ack_count / count if count > 0 else 1.0
if count >= threshold and ratio < 0.3:
alerts.append({
"detection": "SYN Flood",
"target_ip": ip,
"syn_count": count,
"synack_count": ack_count,
"synack_ratio": round(ratio, 4),
"severity": "critical",
})
return alerts
def calculate_entropy(data):
"""Calculate Shannon entropy of a string."""
if not data:
return 0.0
freq = Counter(data)
length = len(data)
return -sum((c / length) * math.log2(c / length) for c in freq.values())
def detect_dns_tunneling(records, length_threshold=50, entropy_threshold=3.5):
"""Detect DNS tunneling via long/high-entropy query names."""
alerts = []
for r in records:
query = r.get("dns_query", "")
if not query:
continue
subdomain = query.split(".")[0] if "." in query else query
if len(subdomain) >= length_threshold or calculate_entropy(subdomain) >= entropy_threshold:
alerts.append({
"detection": "DNS Tunneling Indicator",
"query": query,
"subdomain_length": len(subdomain),
"entropy": round(calculate_entropy(subdomain), 4),
"src_ip": r["src_ip"],
"severity": "high",
})
return alerts
def detect_port_scan(records, threshold=20):
"""Detect port scanning by counting unique destination ports per source IP."""
src_ports = defaultdict(set)
for r in records:
if r.get("tcp_flags") == "S" and r.get("dst_port"):
src_ports[r["src_ip"]].add(r["dst_port"])
alerts = []
for ip, ports in src_ports.items():
if len(ports) >= threshold:
alerts.append({
"detection": "Port Scan",
"source_ip": ip,
"unique_ports_probed": len(ports),
"sample_ports": sorted(list(ports))[:20],
"severity": "high",
})
return alerts
def main():
parser = argparse.ArgumentParser(description="Network Packet Analysis Agent (Scapy)")
parser.add_argument("--pcap", required=True, help="Path to pcap/pcapng file")
parser.add_argument("--syn-threshold", type=int, default=100, help="SYN flood detection threshold")
parser.add_argument("--dns-length", type=int, default=50, help="DNS tunneling subdomain length threshold")
parser.add_argument("--scan-threshold", type=int, default=20, help="Port scan unique ports threshold")
parser.add_argument("--output", default="packet_analysis_report.json", help="Output report path")
args = parser.parse_args()
packets = load_pcap(args.pcap)
records = extract_packet_info(packets)
print(f"[+] Extracted {len(records)} IP-layer records")
stats = compute_traffic_stats(records)
syn_alerts = detect_syn_flood(records, args.syn_threshold)
dns_alerts = detect_dns_tunneling(records, args.dns_length)
scan_alerts = detect_port_scan(records, args.scan_threshold)
report = {
"analysis_time": datetime.utcnow().isoformat() + "Z",
"pcap_file": args.pcap,
"traffic_stats": stats,
"anomalies": {
"syn_flood": syn_alerts,
"dns_tunneling": dns_alerts,
"port_scan": scan_alerts,
},
"total_anomalies": len(syn_alerts) + len(dns_alerts) + len(scan_alerts),
}
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] SYN flood alerts: {len(syn_alerts)}")
print(f"[+] DNS tunneling indicators: {len(dns_alerts)}")
print(f"[+] Port scan detections: {len(scan_alerts)}")
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
FAQ
Is Analyzing Network Packets With Scapy safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.