Skip to content

Instantly share code, notes, and snippets.

@bzamecnik
Created September 28, 2016 14:49
Show Gist options
  • Save bzamecnik/0fb6b2fd2b09aeaf3472224f98e2c4a2 to your computer and use it in GitHub Desktop.
Save bzamecnik/0fb6b2fd2b09aeaf3472224f98e2c4a2 to your computer and use it in GitHub Desktop.
import socket
def netcat(hostname, port):
"""
Reads lines from a network socket and prints them to standard output.
Similar to: netcat $HOST $PORT.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
socket_file = s.makefile()
for line in socket_file:
print(line.strip())
s.close()
netcat('localhost', 12345)
# $ echo -en "foo\nbar\nbaz\n"|netcat -l -p 12345
# $ python python_socket_read_lines.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment