Skip to main content

Short note: Socket programming

Short answer

Socket programming uses the OS socket API (IP address + port) for network communication via TCP or UDP. TCP follows client-server sequence: socket, bind, listen, accept, send/recv, close. UDP uses SOCK_DGRAM with sendto/recvfrom without connection setup. Python example shows simple TCP echo server and client.

Define socket programming. (Short note: Socket programming.)

Socket programming is writing network applications that communicate through sockets, the endpoints of a connection (IP address + port). The program uses the socket API provided by the operating system to send and receive data using TCP or UDP. It follows the client-server model.

TCP socket call sequence

Server                         Client
socket()                       socket()
bind(port)
listen()
accept()  <---- connection --- connect()
recv()    <------ data ------- send()
send()    ------- reply -----> recv()
close()                        close()

Small example (Python, TCP)

# server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0", 5000))
s.listen(1)
conn, addr = s.accept()          # waits for a client
data = conn.recv(1024)           # receive bytes
conn.sendall(data.upper())       # reply
conn.close()

# client.py
import socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("127.0.0.1", 5000))
c.sendall(b"hello")
print(c.recv(1024))              # b'HELLO'
c.close()

For UDP, SOCK_DGRAM is used with sendto() and recvfrom(), and no listen/accept/connect is needed.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Networks and Security chapter 6 questions →