Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

SocketLogger: A class to log all socket traffic. #4893

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
antoniovazquezblanco wants to merge 1 commit into secdev:master
base: master
Choose a base branch
Loading
from antoniovazquezblanco:log
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions scapy/socket_logger.py
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python

# SPDX-License-Identifier: GPL-2.0-only
# This file is part of Scapy
# See https://scapy.net/ for more information

from scapy.supersocket import SuperSocket
from scapy.utils import PcapWriter


class SocketLogger:
"""
A SuperSocket modifier that logs all sent and received packets to a PCAP file.
"""

def __init__(self, sock: SuperSocket, pcap_writer: PcapWriter):
"""
Initialize the Socket Logger.

:param sock: The underlying socket (SuperSocket instance) to log packets from
:param pcap_writer: Configured PcapWriter instance to log packets to
"""
self.sock = sock
self.pcap_writer = pcap_writer
# Backup original send and recv methods
self.sock_send_original = sock.send
self.sock_recv_original = sock.recv
# Attach the logger
self.sock.send = self._send
self.sock.recv = self._recv

def _send(self, pkt):
"""
Send a packet and log it to the PCAP file.

:param pkt: The packet to send
:return: Result of the send operation
"""
len = self.sock_send_original(pkt)
self.pcap_writer.write(pkt)
return len

def _recv(self, x=65535):
"""
Receive a packet and log it to the PCAP file.

:param x: Maximum size to receive
:return: The received packet
"""
pkt = self.sock_recv_original(x)
if pkt:
self.pcap_writer.write(pkt)
return pkt

def close(self):
"""
Close the logger, flush the PCAP writer, and restore original socket methods.
"""
# Restore original methods
self.sock.send = self.sock_send_original
self.sock.recv = self.sock_recv_original
# Close the PCAP writer
self.pcap_writer.close()

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
Loading

AltStyle によって変換されたページ (->オリジナル) /