Skip to content Skip to sidebar Skip to footer

Python One Liner Silent Socket Listener

Is it possible to write python one-liner, which will be listen on specific tcp port, accept connections, and response nothing. I can do this in two lines: import socket; s = socket

Solution 1:

Using itertools.count and reduce (In Python 3.x, you need to use functools.reduce):

import socket, itertools; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(('', 5555)); s.listen(1); accepter = s.accept(); reduce(lambda x, y: accepter[0].recv(1024), itertools.count())

You can also use other infinite iterator like itertools.cycle or itertools.repeat.

Following lines are an expanded version of above one-liner.

import socket, itertoolss= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 5555))
s.listen(1)
accepter = s.accept()
reduce(lambda x, y: accepter[0].recv(1024), itertools.count())

Post a Comment for "Python One Liner Silent Socket Listener"