Show Menu
Cheatography

BlackHat Python Cheat Sheet (DRAFT) by

Small python socket programming cheat sheet. Will add various modules/scapy as I learn more

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Sockets

s = socket.socket (socke­t_f­amily, socket­_type, protoc­ol=0)
socket­_fa­mily: This is either AF_UNIX or AF_INET, as explained earlier.

socket_type: This is either SOCK_S­TREAM or SOCK_D­GRAM.

protocol: This is usually left out, defaulting to 0.
AF_INET: TCPv4 or Hostname

SOCK_D­GRAM: UDP

SOCK_S­TREAM: TCP
Domain
The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
Type
The type of commun­ica­tions between the two endpoints, typically SOCK_S­TREAM for connec­tio­n-o­riented protocols and SOCK_DGRAM for connec­tio­nless protocols.
protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
hostname
The identifier of a network interface:

A string, which can be a host name, a dotted­-quad address, or an IPV6 address in colon (and possibly dot) notation

A string "­<br­oad­cas­t>", which specifies an INADDR­_BR­OADCAST address.

A zero-l­ength string, which specifies INADDR­_ANY, or
An Integer, interp­reted as a binary address in host byte order.
 

Server Socket Methods

s.bind()
This method binds address (hostname, port number pair) to socket.
s.listen()
This method sets up and start TCP listener.
s.accept()
This passively accept TCP client connec­tion, waiting until connection arrives (block­ing).

Client Socket Method

s.conn­ect()
This method actively initiates TCP server connec­tion.

General Socket Method

s.recv()
This method receives TCP message
s.send()
This method transmits TCP message
s.recv­from()
This method receives UDP message
s.sendto()
This method transmits UDP message
s.close()
This method closes socket
socket.ge­tho­stn­ame()
Returns the hostname.
 

Simple Server Example

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

Simple Client Example

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done