<s> import random <EOL> import threading <EOL> from scapy . all import sniff , TCP , send , IP <EOL> class TCPListener ( object ) : <EOL> def __init__ ( self , ip_address = "<STR_LIT:127.0.0.1>" ) : <EOL> self . ip_address = ip_address <EOL> self . source_port = random . randint ( <NUM_LIT> , <NUM_LIT> ) <EOL> self . open_sockets = { } <EOL> self . start_daemon ( ) <EOL> def dispatch ( self , pkt ) : <EOL> if not isinstance ( pkt . payload . payload , TCP ) : <EOL> return <EOL> ip , port = pkt . payload . dst , pkt . dport <EOL> if ip != self . ip_address : <EOL> return <EOL> if ( ip , port ) not in self . open_sockets : <EOL> reset = IP ( src = ip , dst = pkt . payload . src ) / TCP ( seq = pkt . ack , sport = port , dport = pkt . sport , flags = "<STR_LIT:R>" ) <EOL> self . send ( reset ) <EOL> return <EOL> conn = self . open_sockets [ ip , port ] <EOL> conn . handle ( pkt ) <EOL> def send ( self , packet , verbose = <NUM_LIT:0> ) : <EOL> send ( packet , verbose = verbose ) <EOL> def get_port ( self ) : <EOL> self . source_port += <NUM_LIT:1> <EOL> return self . source_port <EOL> def open ( self , ip , port , conn ) : <EOL> self . open_sockets [ ip , port ] = conn <EOL> def close ( self , ip , port ) : <EOL> del self . open_sockets [ ip , port ] <EOL> def listen ( self ) : <EOL> filter_rule = "<STR_LIT>" % self . ip_address <EOL> sniff ( filter = filter_rule , prn = self . dispatch , store = <NUM_LIT:0> ) <EOL> def start_daemon ( self ) : <EOL> t = threading . Thread ( target = self . listen ) <EOL> t . daemon = True <EOL> t . start ( ) </s>
