Created
March 21, 2025 05:13
-
-
Save KnightChaser/531510120d0bf5d7c2a56677fa568e22 to your computer and use it in GitHub Desktop.
The following Python program generates a TCP socket accept event(IPv4) which can be captured by tracing kprobe/inet_csk_accept and kretprobe/inet_csk_accept.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import threading | |
import time | |
# Simple TCP server that listens and accepts a connection. | |
def server(): | |
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
srv.bind(("127.0.0.1", 12345)) | |
srv.listen(5) | |
print("Server: Listening on port 12345...") | |
# This accept() call is where the kernel's inet_csk_accept() is invoked. | |
conn, addr = srv.accept() | |
print(f"Server: Accepted connection from {addr}") | |
conn.sendall(b"Hello, client!") | |
conn.close() | |
srv.close() | |
# Simple TCP client that connects to the server. | |
def client(): | |
time.sleep(1) # Give the server a moment to start listening. | |
cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
cli.connect(("127.0.0.1", 12345)) | |
data = cli.recv(1024) | |
print("Client: Received:", data.decode()) | |
cli.close() | |
if __name__ == "__main__": | |
# Start server and client in separate threads. | |
server_thread = threading.Thread(target=server) | |
client_thread = threading.Thread(target=client) | |
server_thread.start() | |
client_thread.start() | |
server_thread.join() | |
client_thread.join() | |
# eBPF based program will catch the following program's socket event like below. | |
# {"eventname":"tcpV4Accept","source":"eBPF","timestamp":"2025-03-21T14:09:59.506519+09:00","log":"A TCP connection has been accepted","metadata":{"LocalIP":"127.0.0.1","LocalPort":14640,"PID":117642,"RemoteIP":"127.0.0.1","RemotePort":54996,"UID":1000} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment