As seen on late night TV...
import socket sux = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Did I dream this? I could be sure that I wrote this tutorial before but I cannot find it.
To read the official docs about Python sockets go here.
First you start with importing the module:
Then you need to create a
socket object and pass some arguments:
socket.AF_INET: This means
address family internet protocol v4
socket.SOCK_STREAM: This means a
These are the default for IPv4 and TCP:
If you want
If you want
Different socket families use different number of arguments:
AF_INET: A pair-tuple
AF_INET6: A four-tuple
(host, port, flowinfo, scopeid).
You can also use
Closing the socket
If you do this:
import socket sux = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sux.connect( (host, port) )
Then you have to close it like this:
Keep in mind that the argument for
AF_INET) is a pair-tuple:
sux.connect( (host, port) )
You don't need the whitespace but it helps me remember that it needs a tuple. This won't work:
You can also open and close the socket like this:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sux: sux.connect( (host, port) )
Which has a similar syntax as the
with open('simpsons.txt', 'r') as fhandle:
- AF_INET: IPv4
- SOCK_STREAM: TCP
import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sux: sux.connect( (host, port) ) ... something_awesome_here ...