if a program on your computer is connecting to the internet in any way, it's almost certainly using the socket API!
import socket s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) s.connect( ("220.127.116.11", 4321)) s.send(b"hello!")
SOCK_STREAM is used to create TCP connections.
AF_INET means "the internet".
import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) s.sendto(b'hi!', ('127.0.0.1', 1234))
SOCK_DGRAM is used to send UDP packets
import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) s.bind(('0.0.0.0', 1234)) # read 1 packet s.recvfrom(65000)
0.0.0.0 isn't a real IP address. When passed to
bind, it's code for "listen for connections on every
network interface". Often this means the loopback interface
127.0.0.1 etc) and your ethernet/wireless card.
0.0.0.0 is also known as
raw sockets let you send packets with protocols other than UDP or TCP.
ping sends ICMP packets so it needs to use a raw socket.
for example, on Linux, the code that implements TCP and UDP is in the Linux kernel.
one important kind on Unix is "unix domain sockets", which let you listen on/connect to a file instead of an IP address
import socket s = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM) s.bind('/tmp/my.socket') print(s.recvfrom(10000))
it can just write the bytes it wants to send to the socket (like an HTTP response) and the operating system will decide how to split it up into packets.
it'll immediately send a UDP packet with the contents "hello". It won't buffer or anything.
your operating system might instead put "hello" in a buffer, wait for more writes, and combine them into a single TCP packet it sends later. It depends on how you've configured the socket.