Python networking

From wikinotes


TCP Sockets

You can use python to listen and send commands over TCP ports.


WARNING:
This is massively out of date, and does not follow the best practices

References

Very excellent in-depth tutorial about socket programming, and gotchas https://realpython.com/python-sockets/

Listen

NOTE sockets file-descriptors are inherited by multiprocess processes in python 2.7.10. This means you cannot spawn a separate process to restart a tcp server (the TCP connection remain in CLOSE_WAIT until the process dies) You can however do this with threading.

NOTE Also note that the initial 'sock', and the received 'conn' are both socket objects, and require proper closing. Monitor with nestat for problems.


#!/usr/bin/python2
#
# This script listens on port 7085 for incoming connections.
# When a connection is made, it prints the received data
# sends the received data back to the client that sent it 
# and then before shutting down, spawns a new process to listen.

import socket

# sockets do not have an 'End of Transmission' so you have to either
# detect the number of characters being sent and set that as your bufferSize,
# or you can explicitly define your bufferSize beforehand. The Buffer Size 
# only affects how many characters are read from an incoming transmission.
host        = '127.0.0.1'
port        = 7085
buffer_size = 1024


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(( host,port ))
sock.listen(5)										## queue up to 5 connections at once

def portListen():
   conn, addr = sock.accept()
   print 'Connection Addr:', addr			## addr is both host/port
   while True:
      data = conn.recv(buffer_size)
      if data:
         conn.send(data)
         print "received data:", data
         portListen()
			return

      conn.close()  


	## on exit, shutdown reading/writing
	## on both listening/connection sockets, then close
	sock.shutdown( socket.SHUT_RDWR )
	conn.shutdown( socket.SHUT_RDWR ) 
	conn.close()
	sock.close()
	
portListen()

Send

#!/usr/bin/python2
# This script connects to tcp_ip:tcp_port and sends a message.
# It also spits out any data that the daemon sends back to it.
#

import socket

# unlike in daemon, I'm explicitly stating the ip of the machine I
# want to connect to
tcp_ip      = '127.0.0.1'
tcp_port    = 7085
buffer_size = 1024
message     = "Hello world!"

sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
sock.connect((tcp_ip, tcp_port))
sock.send(message)
data = sock.recv(buffer_size)
sock.close()

print data


Socket Files

Socket files are treated exactly the same as INET sockets.

## listen
##

sock        = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
socket_path = '/var/tmp/mysocket'

if os.path.isfile( socket_path ):
	os.remove( socket_path )

socket.bind( socket_path )
sock.listen(1)

(conn,addr) = sock.accept()
while True:
	data = conn.recv(1024)

	## etc ##
## write to socket
##

sock        = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
socket_path = '/var/tmp/mysocket'

sock.connect( socket_path )
sock.send(b'Hi There')
data = sock.recv(1024)
sock.close()
http://benohead.com/tcp-about-fin_wait_2-time_wait-and-close_wait/ Excellent Troubleshooting guide