Lec03 Sockets
Lec03 Sockets
Note: The slides are adapted from the materials from Prof. Richard Han at CU Boulder and Profs. Jennifer Rexford and Mike Freedman at Princeton University,
and the networking book (Computer Networking: A Top Down Approach) from Kurose and Ross.
Programming Assignment #1
• UDP Socket Programming
2
UNIX Sockets
Socket and Process Communication
socket socket
Operating Operating
System System
6
Socket programming
transport transport
network network controlled
link link by OS
Internet
physical physical
Two Types of Application Processes
Communication
11
Client-Server Communication
• Client "sometimes on" • Server is "always on"
– Initiates a request to the – Handles services requests
server when interested from many client hosts
– E.g., Web browser on your – E.g., Web server for the
laptop or cell phone www.cnn.com Web site
– Doesn't communicate – Doesn't initiate contact with
directly with other clients the clients
– Needs to know server's – Needs fixed, known address
address
12
Knowing What Port Number To Use
• Popular applications have well-known ports
– E.g., port 80 for Web and port 25 for e-mail
– See http://www.iana.org/assignments/port-numbers
15
Client-Server Communication
Datagram Sockets (UDP): Connectionless
Server
Client
socket() Create a socket
Create a socket socket()
t)
data (reques Send the request sendto()
recvfrom() Receive Request
data (reply)
sendto() Send response
Receive response recvfrom()
16
Example app: UDP client
Python UDPClient
include Python’s socket library from socket import *
serverName = ‘hostname’
serverPort = 12000
create UDP socket for server clientSocket = socket(AF_INET,
SOCK_DGRAM)
get user keyboard input message = raw_input(’Input lowercase sentence:’)
attach server name, port to message; send into clientSocket.sendto(message.encode(),
socket
(serverName, serverPort))
read reply characters from socket into string modifiedMessage, serverAddress =
clientSocket.recvfrom(2048)
print out received string and close print modifiedMessage.decode()
socket
clientSocket.close()
Example app: UDP server
Python UDPServer
from socket import *
serverPort = 12000
create UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM)
bind socket to local port number 12000 serverSocket.bind(('', serverPort))
print (“The server is ready to receive”)
loop forever while True:
Read from UDP socket into message, message, clientAddress = serverSocket.recvfrom(2048)
getting client’s address (client IP and port)
modifiedMessage = message.decode().upper()
send upper case string back to this client serverSocket.sendto(modifiedMessage.encode(),
clientAddress)
Client-Server Communication
Stream Sockets (TCP): Connection-oriented
Server
socket() Create a socket
( request) send()
data Send the request
recv() Receive Request
Python TCPClient
from socket import *
serverName = ’servername’
serverPort = 12000
create TCP socket for clientSocket = socket(AF_INET, SOCK_STREAM)
server, remote port 12000
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
clientSocket.send(sentence.encode())
No need to attach server name, port modifiedSentence = clientSocket.recv(1024)
print (‘From Server:’, modifiedSentence.decode())
clientSocket.close()
Example app: TCP server
Python TCPServer
from socket import *
serverPort = 12000
create TCP welcoming socket serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((‘’,serverPort))
server begins listening for
incoming TCP requests serverSocket.listen(1)
print ‘The server is ready to receive’
loop forever while True:
server waits on accept() for incoming connectionSocket, addr = serverSocket.accept()
requests, new socket created on return
22
Client: Learning Server Address/Port (cont.)
• Data structure to host address information
struct addrinfo {
int ai_flags;
int ai_family;//e.g. AF_INET for IPv4
int ai_socketype; //e.g. SOCK_STREAM for TCP
int ai_protocol; //e.g. IPPROTO_TCP
size_t ai_addrlen;
char *ai_canonname;
struct sockaddr *ai_addr; // point to sockaddr struct
struct addrinfo *ai_next;
}
• Example
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
int status = getaddrinfo("www.cnn.com", "80", &hints, &result);
// result now points to a linked list of 1 or more addrinfos
// etc.
23
Client: Creating a Socket
• Creating a socket
– int socket(int domain, int type, int protocol)
– Returns a file descriptor (or handle) for the socket
• Domain: protocol family
– PF_INET for IPv4
– PF_INET6 for IPv6
• Type: semantics of the communication
– SOCK_STREAM: reliable byte stream (TCP)
– SOCK_DGRAM: message-oriented service (UDP)
• Protocol: specific protocol
– UNSPEC: unspecified
– (PF_INET and SOCK_STREAM already implies TCP)
• Example
sockfd = socket( result->ai_family,
result->ai_socktype,
result->ai_protocol); 24
Client: Connecting Socket to the Server
• Client contacts the server to establish connection
– Associate the socket with the server address/port
– Acquire a local port number (assigned by the OS)
– Request connection to server, who hopefully accepts
– connect is blocking
• Establishing the connection
– int connect( int sockfd,
struct sockaddr *server_address,
socketlen_t addrlen )
– Args: socket descriptor, server address, and address size
– Returns 0 on success, and -1 if an error occurs
– E.g. connect( sockfd,
result->ai_addr,
result->ai_addrlen); 25
Client: Sending Data
• Sending data
– int send( int sockfd, void *msg,
size_t len, int flags)
26
Client: Receiving Data
• Receiving data
– int recv( int sockfd, void *buf,
size_t len, int flags)
27
Byte Order
• Network byte order
– Big Endian
• When to worry?
– putting data onto the wire
– pulling data off the wire
28
Server: Server Preparing its Socket
• Server creates a socket and binds address/port
– Server creates a socket, just like the client does
– Server associates the socket with the port number
• Create a socket
– int socket( int domain,
int type, int protocol )
29
Server: Allowing Clients to Wait
• Many client requests may arrive
– Server cannot handle them all at the same time
– Server could reject the requests, or let them wait
• Define how many connections can be pending
– int listen(int sockfd, int backlog)
– Arguments: socket descriptor and acceptable backlog
– Returns a 0 on success, and -1 on error
– Listen is non-blocking: returns immediately
• What if too many clients arrive?
– Some requests don't get through
– The Internet makes no promises…
– And the client can always try again
30
Server: Accepting Client Connection
• Now all the server can do is wait…
– Waits for connection request to arrive
– Blocking until the request arrives
– And then accepting the new request
34
while (1) {
fd = accept (srv_fd, (struct sockaddr *) &caddr, &clen);
...
pid = fork(); children++;
/* child process to handle request */
if (pid == 0) {
/* exit(0) on success, exit(1) on error */
}
/* parent process */
else if (pid > 0) {
while ((waitpid(-1, &status, WNOHANG)) > 0)
children--;
if (children > MAX_PROCESSES)
...
}
else {
perror("ERROR on fork");
exit(1);
}}
35
udpclient.c
36
udpserver.c
37
tcpechoserver.c
38
tcpechoclient.c
39
Debugging with netcat (nc)
• UDP
– nc –u –l localhost 9999 # listening from UDP port 9999
– nc –u localhost 9999 # connect and send data to port 999
• TCP
– nc –lv localhost 9999 # listening from TCP port 9999
– nc localhost 9999 # connect and send data to TCP port 999
40
Helpful Links
41