SlideShare a Scribd company logo
15-441: Computer Networking
Lecture 3: Application Layer and
Socket Programming
Lecture 3: 9-4-01 2
Lecture Overview
โ€ข Application layer
โ€ข Client-server
โ€ข Application requirements
โ€ข Background
โ€ข TCP vs. UDP
โ€ข Byte ordering
โ€ข Socket I/O
โ€ข TCP/UDP server and client
โ€ข I/O multiplexing
Lecture 3: 9-4-01 3
Applications and Application-Layer
Protocols
โ€ข Application: communicating,
distributed processes
โ€ข Running in network hosts in
โ€œuser spaceโ€
โ€ข Exchange messages to
implement app
โ€ข e.g., email, file transfer, the
Web
โ€ข Application-layer protocols
โ€ข One โ€œpieceโ€ of an app
โ€ข Define messages exchanged
by apps and actions taken
โ€ข User services provided by
lower layer protocols
application
transport
network
data link
physical
application
transport
network
data link
physical
application
transport
network
data link
physical
Lecture 3: 9-4-01 4
Client-Server Paradigm
Typical network app has two pieces: client and server
application
transport
network
data link
physical
application
transport
network
data link
physical
Client:
โ€ข Initiates contact with server
(โ€œspeaks firstโ€)
โ€ข Typically requests service from
server,
โ€ข For Web, client is implemented in
browser; for e-mail, in mail reader
Server:
โ€ข Provides requested service to
client
โ€ข e.g., Web server sends
requested Web page, mail server
delivers e-mail
request
reply
Lecture 3: 9-4-01 5
Ftp: The File Transfer Protocol
โ€ข Transfer file to/from remote host
โ€ข Client/server model
โ€ข Client: side that initiates transfer (either to/from remote)
โ€ข Server: remote host
โ€ข ftp: RFC 959
โ€ข ftp server: port 21
file transfer
FTP
server
FTP
user
interface
FTP
client
local file
system
remote file
system
user
at host
Lecture 3: 9-4-01 6
Ftp: Separate Control, Data
Connections
โ€ข Ftp client contacts ftp server
at port 21, specifying TCP
as transport protocol
โ€ข Two parallel TCP
connections opened:
โ€ข Control: exchange commands,
responses between client,
server.
โ€œout of band controlโ€
โ€ข Data: file data to/from server
โ€ข Ftp server maintains โ€œstateโ€:
current directory, earlier
authentication
FTP
client
FTP
server
TCP control connection
port 21
TCP data connection
port 20
Lecture 3: 9-4-01 7
Ftp Commands, Responses
Sample Commands:
โ€ข sent as ASCII text over
control channel
โ€ข USER username
โ€ข PASS password
โ€ข LIST return list of files in
current directory
โ€ข RETR filename
retrieves (gets) file
โ€ข STOR filename stores
(puts) file onto remote host
Sample Return Codes
โ€ข status code and phrase
โ€ข 331 Username OK,
password required
โ€ข 125 data connection
already open;
transfer starting
โ€ข 425 Canโ€™t open data
connection
โ€ข 452 Error writing
file
Lecture 3: 9-4-01 8
What Transport Service Does an
Application Need?
Data loss
โ€ข Some apps (e.g., audio) can
tolerate some loss
โ€ข Other apps (e.g., file transfer,
telnet) require 100% reliable
data transfer
Timing
โ€ข Some apps (e.g., Internet
telephony, interactive
games) require low delay to
be โ€œeffectiveโ€
Bandwidth
โ€ข Some apps (e.g., multimedia) require minimum amount of
bandwidth to be โ€œeffectiveโ€
โ€ข Other apps (โ€œelastic appsโ€) make use of whatever bandwidth they
get
Lecture 3: 9-4-01 9
Transport Service Requirements
of Common Apps
no loss
no loss
no loss
loss-tolerant
loss-tolerant
loss-tolerant
no loss
elastic
elastic
elastic
audio: 5Kb-1Mb
video:10Kb-5Mb
same as above
few Kbps
elastic
no
no
no
yes, 100โ€™s msec
yes, few secs
yes, 100โ€™s msec
yes and no
file transfer
e-mail
web documents
real-time audio/
video
stored audio/video
interactive games
financial apps
Application Data loss Bandwidth Time Sensitive
Lecture 3: 9-4-01 10
Lecture Overview
โ€ข Application layer
โ€ข Client-server
โ€ข Application requirements
โ€ข Background
โ€ข TCP vs. UDP
โ€ข Byte ordering
โ€ข Socket I/O
โ€ข TCP/UDP server and client
โ€ข I/O multiplexing
Lecture 3: 9-4-01 11
Server and Client
TCP/UDP
IP
Ethernet Adapter
Server
TCP/UDP
IP
Ethernet Adapter
Clients
Server and Client exchange messages over the
network through a common Socket API
Socket API
hardware
kernel
space
user
space
ports
Lecture 3: 9-4-01 12
User Datagram Protocol(UDP):
An Analogy
Postal Mail
โ€ข Single mailbox to receive
messages
โ€ข Unreliable ๏Š
โ€ข Not necessarily in-order
delivery
โ€ข Each letter is independent
โ€ข Must address each reply
Example UDP applications
Multimedia, voice over IP
UDP
โ€ข Single socket to receive
messages
โ€ข No guarantee of delivery
โ€ข Not necessarily in-order
delivery
โ€ข Datagram โ€“ independent
packets
โ€ข Must address each packet
Postal Mail
โ€ข Single mailbox to receive
letters
โ€ข Unreliable ๏Š
โ€ข Not necessarily in-order
delivery
โ€ข Letters sent independently
โ€ข Must address each reply
Lecture 3: 9-4-01 13
Transmission Control Protocol
(TCP): An Analogy
TCP
โ€ข Reliable โ€“ guarantee
delivery
โ€ข Byte stream โ€“ in-order
delivery
โ€ข Connection-oriented โ€“
single socket per
connection
โ€ข Setup connection
followed by data transfer
Telephone Call
โ€ข Guaranteed delivery
โ€ข In-order delivery
โ€ข Connection-oriented
โ€ข Setup connection
followed by conversation
Example TCP applications
Web, Email, Telnet
Lecture 3: 9-4-01 14
Network Addressing Analogy
412-268-8000
ext.123
Central Number
Applications/Servers
Web
Port 80
Mail
Port 25
Exchange
Area Code
412-268-8000
ext.654
IP Address
Network No.
Host Number
Telephone No
15-441 Students Clients
Professors at CMU
Network Programming
Telephone Call
Port No.
Extension
Lecture 3: 9-4-01 15
Concept of Port Numbers
โ€ข Port numbers are used to identify
โ€œentitiesโ€ on a host
โ€ข Port numbers can be
โ€ข Well-known (port 0-1023)
โ€ข Dynamic or private (port 1024-65535)
โ€ข Servers/daemons usually use well-
known ports
โ€ข Any client can identify the server/service
โ€ข HTTP = 80, FTP = 21, Telnet = 23, ...
โ€ข /etc/service defines well-known ports
โ€ข Clients usually use dynamic ports
โ€ข Assigned by the kernel at run time
TCP/UDP
IP
Ethernet Adapter
NTP
daemon
Web
server
port 123 port 80
Lecture 3: 9-4-01 16
Names and Addresses
โ€ข Each attachment point on Internet is given
unique address
โ€ข Based on location within network โ€“ like phone
numbers
โ€ข Humans prefer to deal with names not
addresses
โ€ข DNS provides mapping of name to address
โ€ข Name based on administrative ownership of
host
Lecture 3: 9-4-01 17
#include <netinet/in.h>
/* Internet address structure */
struct in_addr {
u_long s_addr; /* 32-bit IPv4 address */
}; /* network byte ordered */
/* Socket address, Internet style. */
struct sockaddr_in {
u_char sin_family; /* Address Family */
u_short sin_port; /* UDP or TCP Port# */
/* network byte ordered */
struct in_addr sin_addr; /* Internet Address */
char sin_zero[8]; /* unused */
};
Internet Addressing Data Structure
โ€ข sin_family = AF_INET selects Internet address family
Lecture 3: 9-4-01 18
Byte Ordering
โ€ข Big Endian
โ€ข Sun Solaris, PowerPC, ...
โ€ข Little Endian
โ€ข i386, alpha, ...
โ€ข Network byte order = Big Endian
128 2 194 95
union {
u_int32_t addr; /* 4 bytes address */
char c[4];
} un;
/* 128.2.194.95 */
un.addr = 0x8002c25f;
/* c[0] = ? */
c[0] c[1] c[2] c[3]
95 194 2 128
Lecture 3: 9-4-01 19
Byte Ordering Functions
โ€ข Converts between host byte order and network
byte order
โ€ข โ€˜hโ€™ = host byte order
โ€ข โ€˜nโ€™ = network byte order
โ€ข โ€˜lโ€™ = long (4 bytes), converts IP addresses
โ€ข โ€˜sโ€™ = short (2 bytes), converts port numbers
#include <netinet/in.h>
unsigned long int htonl(unsigned long int hostlong);
unsigned short int htons(unsigned short int
hostshort);
unsigned long int ntohl(unsigned long int netlong);
unsigned short int ntohs(unsigned short int
netshort);
Lecture 3: 9-4-01 20
Lecture Overview
โ€ข Application layer
โ€ข Client-server
โ€ข Application requirements
โ€ข Background
โ€ข TCP vs. UDP
โ€ข Byte ordering
โ€ข Socket I/O
โ€ข TCP/UDP server and client
โ€ข I/O multiplexing
Lecture 3: 9-4-01 21
โ€ข A socket is a file descriptor that lets an application read/write data
from/to the network
โ€ข socket returns an integer (socket descriptor)
โ€ข fd < 0 indicates that an error occurred
โ€ข socket descriptors are similar to file descriptors
โ€ข AF_INET: associates a socket with the Internet protocol family
โ€ข SOCK_STREAM: selects the TCP protocol
โ€ข SOCK_DGRAM: selects the UDP protocol
What is a Socket?
int fd; /* socket descriptor */
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) }
perror(โ€œsocketโ€);
exit(1);
}
Lecture 3: 9-4-01 22
TCP
IP
Ethernet Adapter
Web Server
Port 80
โ€ข For example: web
server
โ€ข What does a web server
need to do so that a web
client can connect to it?
TCP Server
Lecture 3: 9-4-01 23
โ€ข Since web traffic uses TCP, the web server must create a socket of type
SOCK_STREAM
int fd; /* socket descriptor */
if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror(โ€œsocketโ€);
exit(1);
}
โ€ข socket returns an integer (socket descriptor)
โ€ข fd < 0 indicates that an error occurred
โ€ข AF_INET associates a socket with the Internet protocol family
โ€ข SOCK_STREAM selects the TCP protocol
Socket I/O: socket()
Lecture 3: 9-4-01 24
โ€ข A socket can be bound to a port
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
/* create the socket */
srv.sin_family = AF_INET; /* use the Internet addr family */
srv.sin_port = htons(80); /* bind socket โ€˜fdโ€™ to port 80*/
/* bind: a client may connect to any of my addresses */
srv.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) {
perror("bind"); exit(1);
}
โ€ข Still not quite ready to communicate with a client...
Socket I/O: bind()
Lecture 3: 9-4-01 25
Socket I/O: listen()
โ€ข listen indicates that the server will accept a connection
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
/* 1) create the socket */
/* 2) bind the socket to a port */
if(listen(fd, 5) < 0) {
perror(โ€œlistenโ€);
exit(1);
}
โ€ข Still not quite ready to communicate with a client...
Lecture 3: 9-4-01 26
Socket I/O: accept()
โ€ข accept blocks waiting for a connection
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
struct sockaddr_in cli; /* used by accept() */
int newfd; /* returned by accept() */
int cli_len = sizeof(cli); /* used by accept() */
/* 1) create the socket */
/* 2) bind the socket to a port */
/* 3) listen on the socket */
newfd = accept(fd, (struct sockaddr*) &cli, &cli_len);
if(newfd < 0) {
perror("accept"); exit(1);
}
โ€ข accept returns a new socket (newfd) with the same properties as the
original socket (fd)
โ€ข newfd < 0 indicates that an error occurred
Lecture 3: 9-4-01 27
Socket I/O: accept() continued...
struct sockaddr_in cli; /* used by accept() */
int newfd; /* returned by accept() */
int cli_len = sizeof(cli); /* used by accept() */
newfd = accept(fd, (struct sockaddr*) &cli, &cli_len);
if(newfd < 0) {
perror("accept");
exit(1);
}
โ€ข How does the server know which client it is?
โ€ข cli.sin_addr.s_addr contains the clientโ€™s IP address
โ€ข cli.sin_port contains the clientโ€™s port number
โ€ข Now the server can exchange data with the client by
using read and write on the descriptor newfd.
โ€ข Why does accept need to return a new descriptor?
Lecture 3: 9-4-01 28
Socket I/O: read()
โ€ข read can be used with a socket
โ€ข read blocks waiting for data from the client but
does not guarantee that sizeof(buf) is read
int fd; /* socket descriptor */
char buf[512]; /* used by read() */
int nbytes; /* used by read() */
/* 1) create the socket */
/* 2) bind the socket to a port */
/* 3) listen on the socket */
/* 4) accept the incoming connection */
if((nbytes = read(newfd, buf, sizeof(buf))) < 0) {
perror(โ€œreadโ€); exit(1);
}
Lecture 3: 9-4-01 29
TCP
IP
Ethernet Adapter
2 Web Clients
TCP Client
โ€ข For example: web
client
โ€ข How does a web client
connect to a web server?
Lecture 3: 9-4-01 30
struct sockaddr_in srv;
srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€);
if(srv.sin_addr.s_addr == (in_addr_t) -1) {
fprintf(stderr, "inet_addr failed!n"); exit(1);
}
Converting a numerical address to a string:
Dealing with IP Addresses
โ€ข IP Addresses are commonly written as strings (โ€œ128.2.35.50โ€), but
programs deal with IP addresses as integers.
struct sockaddr_in srv;
char *t = inet_ntoa(srv.sin_addr);
if(t == 0) {
fprintf(stderr, โ€œinet_ntoa failed!nโ€); exit(1);
}
Converting strings to numerical address:
Lecture 3: 9-4-01 31
Translating Names to Addresses
โ€ข Gethostbyname provides interface to DNS
โ€ข Additional useful calls
โ€ข Gethostbyaddr โ€“ returns hostent given sockaddr_in
โ€ข Getservbyname
โ€ข Used to get service description (typically port number)
โ€ข Returns servent based on name
#include <netdb.h>
struct hostent *hp; /*ptr to host info for remote*/
struct sockaddr_in peeraddr;
char *name = โ€œwww.cs.cmu.eduโ€;
peeraddr.sin_family = AF_INET;
hp = gethostbyname(name)
peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;
Lecture 3: 9-4-01 32
Socket I/O: connect()
โ€ข connect allows a client to connect to a server...
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by connect() */
/* create the socket */
/* connect: use the Internet address family */
srv.sin_family = AF_INET;
/* connect: socket โ€˜fdโ€™ to port 80 */
srv.sin_port = htons(80);
/* connect: connect to IP Address โ€œ128.2.35.50โ€ */
srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€);
if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) {
perror(โ€connect"); exit(1);
}
Lecture 3: 9-4-01 33
Socket I/O: write()
โ€ข write can be used with a socket
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by connect() */
char buf[512]; /* used by write() */
int nbytes; /* used by write() */
/* 1) create the socket */
/* 2) connect() to the server */
/* Example: A client could โ€œwriteโ€ a request to a server
*/
if((nbytes = write(fd, buf, sizeof(buf))) < 0) {
perror(โ€œwriteโ€);
exit(1);
}
Lecture 3: 9-4-01 34
Review: TCP Client-Server
Interaction
socket()
bind()
listen()
accept()
write()
read()
read()
TCP Server
close()
socket()
TCP Client
connect()
write()
read()
close()
connection establishment
data request
data reply
end-of-file notification
from UNIX Network Programming Volume 1, figure 4.1
Lecture 3: 9-4-01 35
UDP
IP
Ethernet Adapter
NTP
daemon
UDP Server Example
Port 123
โ€ข For example: NTP
daemon
โ€ข What does a UDP server
need to do so that a UDP
client can connect to it?
Lecture 3: 9-4-01 36
Socket I/O: socket()
โ€ข The UDP server must create a datagram socketโ€ฆ
int fd; /* socket descriptor */
if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror(โ€œsocketโ€);
exit(1);
}
โ€ข socket returns an integer (socket descriptor)
โ€ข fd < 0 indicates that an error occurred
โ€ข AF_INET: associates a socket with the Internet protocol family
โ€ข SOCK_DGRAM: selects the UDP protocol
Lecture 3: 9-4-01 37
Socket I/O: bind()
โ€ข A socket can be bound to a port
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
/* create the socket */
/* bind: use the Internet address family */
srv.sin_family = AF_INET;
/* bind: socket โ€˜fdโ€™ to port 80*/
srv.sin_port = htons(80);
/* bind: a client may connect to any of my addresses */
srv.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) {
perror("bind"); exit(1);
}
โ€ข Now the UDP server is ready to accept packetsโ€ฆ
Lecture 3: 9-4-01 38
Socket I/O: recvfrom()
โ€ข read does not provide the clientโ€™s address to the UDP server
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by bind() */
struct sockaddr_in cli; /* used by recvfrom() */
char buf[512]; /* used by recvfrom() */
int cli_len = sizeof(cli); /* used by recvfrom() */
int nbytes; /* used by recvfrom() */
/* 1) create the socket */
/* 2) bind to the socket */
nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */,
(struct sockaddr*) &cli, &cli_len);
if(nbytes < 0) {
perror(โ€œrecvfromโ€); exit(1);
}
Lecture 3: 9-4-01 39
Socket I/O: recvfrom() continued...
nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */,
(struct sockaddr*) cli, &cli_len);
โ€ข The actions performed by recvfrom
โ€ข returns the number of bytes read (nbytes)
โ€ข copies nbytes of data into buf
โ€ข returns the address of the client (cli)
โ€ข returns the length of cli (cli_len)
โ€ข donโ€™t worry about flags
Lecture 3: 9-4-01 40
TCP
IP
Ethernet Adapter
2 UDP Clients
UDP Client Example
ports
โ€ข How does a UDP client
communicate with a UDP
server?
Lecture 3: 9-4-01 41
Socket I/O: sendto()
โ€ข write is not allowed
โ€ข Notice that the UDP client does not bind a port number
โ€ข a port number is dynamically assigned when the first sendto is called
int fd; /* socket descriptor */
struct sockaddr_in srv; /* used by sendto() */
/* 1) create the socket */
/* sendto: send data to IP Address โ€œ128.2.35.50โ€ port 80 */
srv.sin_family = AF_INET;
srv.sin_port = htons(80);
srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€);
nbytes = sendto(fd, buf, sizeof(buf), 0 /* flags */,
(struct sockaddr*) &srv, sizeof(srv));
if(nbytes < 0) {
perror(โ€œsendtoโ€); exit(1);
}
Lecture 3: 9-4-01 42
Review: UDP Client-Server
Interaction
socket()
bind()
recvfrom()
sendto()
UDP Server
socket()
UDP Client
sendto()
recvfrom()
close()
blocks until datagram
received from a client
data request
data reply
from UNIX Network Programming Volume 1, figure 8.1
Lecture 3: 9-4-01 43
UDP
IP
Ethernet Adapter
UDP Server
The UDP Server
Port 2000
Port 3000
โ€ข How can the UDP server
service multiple ports
simultaneously?
Lecture 3: 9-4-01 44
int s1; /* socket descriptor 1 */
int s2; /* socket descriptor 2 */
/* 1) create socket s1 */
/* 2) create socket s2 */
/* 3) bind s1 to port 2000 */
/* 4) bind s2 to port 3000 */
while(1) {
recvfrom(s1, buf, sizeof(buf), ...);
/* process buf */
recvfrom(s2, buf, sizeof(buf), ...);
/* process buf */
}
UDP Server: Servicing Two Ports
โ€ข What problems does this code have?
Lecture 3: 9-4-01 45
Socket I/O: select()
int select(int maxfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
FD_CLR(int fd, fd_set *fds); /* clear the bit for fd in fds */
FD_ISSET(int fd, fd_set *fds); /* is the bit for fd in fds? */
FD_SET(int fd, fd_set *fds); /* turn on the bit for fd in fds */
FD_ZERO(fd_set *fds); /* clear all bits in fds */
โ€ข maxfds: number of descriptors to be tested
โ€ข descriptors (0, 1, ... maxfds-1) will be tested
โ€ข readfds: a set of fds we want to check if data is available
โ€ข returns a set of fds ready to read
โ€ข if input argument is NULL, not interested in that condition
โ€ข writefds: returns a set of fds ready to write
โ€ข exceptfds: returns a set of fds with exception conditions
Lecture 3: 9-4-01 46
Socket I/O: select()
int select(int maxfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
struct timeval {
long tv_sec; /* seconds /
long tv_usec; /* microseconds */
}
โ€ข timeout
โ€ข if NULL, wait forever and return only when one of the descriptors is
ready for I/O
โ€ข otherwise, wait up to a fixed amount of time specified by timeout
โ€ข if we donโ€™t want to wait at all, create a timeout structure with timer value
equal to 0
โ€ข Refer to the man page for more information
Lecture 3: 9-4-01 47
int s1, s2; /* socket descriptors */
fd_set readfds; /* used by select() */
/* create and bind s1 and s2 */
while(1) {
FD_ZERO(&readfds); /* initialize the fd set
*/
FD_SET(s1, &readfds); /* add s1 to the fd set */
FD_SET(s2, &readfds); /* add s2 to the fd set */
if(select(s2+1, &readfds, 0, 0, 0) < 0) {
perror(โ€œselectโ€);
exit(1);
}
if(FD_ISSET(s1, &readfds)) {
recvfrom(s1, buf, sizeof(buf), ...);
/* process buf */
}
/* do the same for s2 */
}
Socket I/O: select()
โ€ข select allows synchronous I/O multiplexing
Lecture 3: 9-4-01 48
TCP
IP
Ethernet Adapter
Web Server
Port 80
How can a a web server manage
multiple connections simultaneously?
Port 8001
More Details About a Web Server
Lecture 3: 9-4-01 49
int fd, next=0; /* original socket */
int newfd[10]; /* new socket descriptors */
while(1) {
fd_set readfds;
FD_ZERO(&readfds); FD_SET(fd, &readfds);
/* Now use FD_SET to initialize other newfdโ€™s
that have already been returned by accept() */
select(maxfd+1, &readfds, 0, 0, 0);
if(FD_ISSET(fd, &readfds)) {
newfd[next++] = accept(fd, ...);
}
/* do the following for each descriptor newfd[n] */
if(FD_ISSET(newfd[n], &readfds)) {
read(newfd[n], buf, sizeof(buf));
/* process data */
}
}
Socket I/O: select()
โ€ข Now the web server can support multiple connections...
Lecture 3: 9-4-01 50
A Few Programming Notes:
Representing Packets
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Length | Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Type: 4-byte integer
Length: 2-byte integer
Checksum: 2-byte integer
Address: 4-byte IP address
Lecture 3: 9-4-01 51
A Few Programming Notes:
Building a Packet in a Buffer
struct packet {
u_int32_t type;
u_int16_t length;
u_int16_t checksum;
u_int32_t address;
};
/* ================================================== */
char buf[1024];
struct packet *pkt;
pkt = (struct packet*) buf;
pkt->type = htonl(1);
pkt->length = htons(2);
pkt->checksum = htons(3);
pkt->address = htonl(4);
Lecture 3: 9-4-01 52
Socket Programming References
โ€ข Man page
โ€ข usage: man <function name>
โ€ข Textbook
โ€ข Sections 2.6, 2.7
โ€ข demo programs written in Java
โ€ข Unix Network Programming : Networking
APIs: Sockets and XTI (Volume 1)
โ€ข Section 2, 3, 4, 6, 8
โ€ข ultimate socket programming bible!

More Related Content

Similar to lecture03for socket programming college.ppt (20)

PDF
+ Network Programming.pdf
OluwafolakeOjo
ย 
PPT
Sockets
Gopaiah Sanaka
ย 
PDF
network programming lab manuaal in this file
shivani158351
ย 
PPT
Socket Programming
CEC Landran
ย 
PPT
03 sockets
Pavan Illa
ย 
PPT
sockets_intro.ppt
AnilGupta681764
ย 
PDF
Socket programming using C
Ajit Nayak
ย 
PDF
Socket Programming
elliando dias
ย 
PPTX
Basics of sockets
AviNash ChaVhan
ย 
PPT
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
ย 
PPTX
L5-Sockets.pptx
ycelgemici1
ย 
PPT
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
ย 
PPT
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
ย 
PPT
Socket programming
Divya Sharma
ย 
PPT
Socket programming in C
Deepak Swain
ย 
PPTX
Network Programming-Python-13-8-2023.pptx
ssuser23035c
ย 
PDF
CS6551 COMPUTER NETWORKS
Kathirvel Ayyaswamy
ย 
PPTX
Introduction to socket programming nbv
Nagasuri Bala Venkateswarlu
ย 
PDF
lab04.pdf
SaidiCalala
ย 
PPT
Sockets intro
AviNash ChaVhan
ย 
+ Network Programming.pdf
OluwafolakeOjo
ย 
Sockets
Gopaiah Sanaka
ย 
network programming lab manuaal in this file
shivani158351
ย 
Socket Programming
CEC Landran
ย 
03 sockets
Pavan Illa
ย 
sockets_intro.ppt
AnilGupta681764
ย 
Socket programming using C
Ajit Nayak
ย 
Socket Programming
elliando dias
ย 
Basics of sockets
AviNash ChaVhan
ย 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
ย 
L5-Sockets.pptx
ycelgemici1
ย 
LECTURE-17(Socket Programming) Detailed.
qamarmajeed0000
ย 
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
ย 
Socket programming
Divya Sharma
ย 
Socket programming in C
Deepak Swain
ย 
Network Programming-Python-13-8-2023.pptx
ssuser23035c
ย 
CS6551 COMPUTER NETWORKS
Kathirvel Ayyaswamy
ย 
Introduction to socket programming nbv
Nagasuri Bala Venkateswarlu
ย 
lab04.pdf
SaidiCalala
ย 
Sockets intro
AviNash ChaVhan
ย 

Recently uploaded (20)

PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
ย 
PPTX
internet bรกsico presentacion es una red global
70965857
ย 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
ย 
PDF
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
Cerebraix Technologies
ย 
PDF
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
ย 
PPTX
Orchestrating things in Angular application
Peter Abraham
ย 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
ย 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
ย 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
ย 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
ย 
PDF
๐๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“
hokimamad0
ย 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
ย 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
ย 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
ย 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
ย 
PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
ย 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
ย 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
ย 
PDF
Paper: Quantum Financial System - DeFi patent wars
Steven McGee
ย 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
ย 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
ย 
internet bรกsico presentacion es una red global
70965857
ย 
introductio to computers by arthur janry
RamananMuthukrishnan
ย 
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
Cerebraix Technologies
ย 
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
ย 
Orchestrating things in Angular application
Peter Abraham
ย 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
ย 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
ย 
introduction to networking with basics coverage
RamananMuthukrishnan
ย 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
ย 
๐๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“
hokimamad0
ย 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
ย 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
ย 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
ย 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
ย 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
ย 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
ย 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
ย 
Paper: Quantum Financial System - DeFi patent wars
Steven McGee
ย 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
ย 
Ad

lecture03for socket programming college.ppt

  • 1. 15-441: Computer Networking Lecture 3: Application Layer and Socket Programming
  • 2. Lecture 3: 9-4-01 2 Lecture Overview โ€ข Application layer โ€ข Client-server โ€ข Application requirements โ€ข Background โ€ข TCP vs. UDP โ€ข Byte ordering โ€ข Socket I/O โ€ข TCP/UDP server and client โ€ข I/O multiplexing
  • 3. Lecture 3: 9-4-01 3 Applications and Application-Layer Protocols โ€ข Application: communicating, distributed processes โ€ข Running in network hosts in โ€œuser spaceโ€ โ€ข Exchange messages to implement app โ€ข e.g., email, file transfer, the Web โ€ข Application-layer protocols โ€ข One โ€œpieceโ€ of an app โ€ข Define messages exchanged by apps and actions taken โ€ข User services provided by lower layer protocols application transport network data link physical application transport network data link physical application transport network data link physical
  • 4. Lecture 3: 9-4-01 4 Client-Server Paradigm Typical network app has two pieces: client and server application transport network data link physical application transport network data link physical Client: โ€ข Initiates contact with server (โ€œspeaks firstโ€) โ€ข Typically requests service from server, โ€ข For Web, client is implemented in browser; for e-mail, in mail reader Server: โ€ข Provides requested service to client โ€ข e.g., Web server sends requested Web page, mail server delivers e-mail request reply
  • 5. Lecture 3: 9-4-01 5 Ftp: The File Transfer Protocol โ€ข Transfer file to/from remote host โ€ข Client/server model โ€ข Client: side that initiates transfer (either to/from remote) โ€ข Server: remote host โ€ข ftp: RFC 959 โ€ข ftp server: port 21 file transfer FTP server FTP user interface FTP client local file system remote file system user at host
  • 6. Lecture 3: 9-4-01 6 Ftp: Separate Control, Data Connections โ€ข Ftp client contacts ftp server at port 21, specifying TCP as transport protocol โ€ข Two parallel TCP connections opened: โ€ข Control: exchange commands, responses between client, server. โ€œout of band controlโ€ โ€ข Data: file data to/from server โ€ข Ftp server maintains โ€œstateโ€: current directory, earlier authentication FTP client FTP server TCP control connection port 21 TCP data connection port 20
  • 7. Lecture 3: 9-4-01 7 Ftp Commands, Responses Sample Commands: โ€ข sent as ASCII text over control channel โ€ข USER username โ€ข PASS password โ€ข LIST return list of files in current directory โ€ข RETR filename retrieves (gets) file โ€ข STOR filename stores (puts) file onto remote host Sample Return Codes โ€ข status code and phrase โ€ข 331 Username OK, password required โ€ข 125 data connection already open; transfer starting โ€ข 425 Canโ€™t open data connection โ€ข 452 Error writing file
  • 8. Lecture 3: 9-4-01 8 What Transport Service Does an Application Need? Data loss โ€ข Some apps (e.g., audio) can tolerate some loss โ€ข Other apps (e.g., file transfer, telnet) require 100% reliable data transfer Timing โ€ข Some apps (e.g., Internet telephony, interactive games) require low delay to be โ€œeffectiveโ€ Bandwidth โ€ข Some apps (e.g., multimedia) require minimum amount of bandwidth to be โ€œeffectiveโ€ โ€ข Other apps (โ€œelastic appsโ€) make use of whatever bandwidth they get
  • 9. Lecture 3: 9-4-01 9 Transport Service Requirements of Common Apps no loss no loss no loss loss-tolerant loss-tolerant loss-tolerant no loss elastic elastic elastic audio: 5Kb-1Mb video:10Kb-5Mb same as above few Kbps elastic no no no yes, 100โ€™s msec yes, few secs yes, 100โ€™s msec yes and no file transfer e-mail web documents real-time audio/ video stored audio/video interactive games financial apps Application Data loss Bandwidth Time Sensitive
  • 10. Lecture 3: 9-4-01 10 Lecture Overview โ€ข Application layer โ€ข Client-server โ€ข Application requirements โ€ข Background โ€ข TCP vs. UDP โ€ข Byte ordering โ€ข Socket I/O โ€ข TCP/UDP server and client โ€ข I/O multiplexing
  • 11. Lecture 3: 9-4-01 11 Server and Client TCP/UDP IP Ethernet Adapter Server TCP/UDP IP Ethernet Adapter Clients Server and Client exchange messages over the network through a common Socket API Socket API hardware kernel space user space ports
  • 12. Lecture 3: 9-4-01 12 User Datagram Protocol(UDP): An Analogy Postal Mail โ€ข Single mailbox to receive messages โ€ข Unreliable ๏Š โ€ข Not necessarily in-order delivery โ€ข Each letter is independent โ€ข Must address each reply Example UDP applications Multimedia, voice over IP UDP โ€ข Single socket to receive messages โ€ข No guarantee of delivery โ€ข Not necessarily in-order delivery โ€ข Datagram โ€“ independent packets โ€ข Must address each packet Postal Mail โ€ข Single mailbox to receive letters โ€ข Unreliable ๏Š โ€ข Not necessarily in-order delivery โ€ข Letters sent independently โ€ข Must address each reply
  • 13. Lecture 3: 9-4-01 13 Transmission Control Protocol (TCP): An Analogy TCP โ€ข Reliable โ€“ guarantee delivery โ€ข Byte stream โ€“ in-order delivery โ€ข Connection-oriented โ€“ single socket per connection โ€ข Setup connection followed by data transfer Telephone Call โ€ข Guaranteed delivery โ€ข In-order delivery โ€ข Connection-oriented โ€ข Setup connection followed by conversation Example TCP applications Web, Email, Telnet
  • 14. Lecture 3: 9-4-01 14 Network Addressing Analogy 412-268-8000 ext.123 Central Number Applications/Servers Web Port 80 Mail Port 25 Exchange Area Code 412-268-8000 ext.654 IP Address Network No. Host Number Telephone No 15-441 Students Clients Professors at CMU Network Programming Telephone Call Port No. Extension
  • 15. Lecture 3: 9-4-01 15 Concept of Port Numbers โ€ข Port numbers are used to identify โ€œentitiesโ€ on a host โ€ข Port numbers can be โ€ข Well-known (port 0-1023) โ€ข Dynamic or private (port 1024-65535) โ€ข Servers/daemons usually use well- known ports โ€ข Any client can identify the server/service โ€ข HTTP = 80, FTP = 21, Telnet = 23, ... โ€ข /etc/service defines well-known ports โ€ข Clients usually use dynamic ports โ€ข Assigned by the kernel at run time TCP/UDP IP Ethernet Adapter NTP daemon Web server port 123 port 80
  • 16. Lecture 3: 9-4-01 16 Names and Addresses โ€ข Each attachment point on Internet is given unique address โ€ข Based on location within network โ€“ like phone numbers โ€ข Humans prefer to deal with names not addresses โ€ข DNS provides mapping of name to address โ€ข Name based on administrative ownership of host
  • 17. Lecture 3: 9-4-01 17 #include <netinet/in.h> /* Internet address structure */ struct in_addr { u_long s_addr; /* 32-bit IPv4 address */ }; /* network byte ordered */ /* Socket address, Internet style. */ struct sockaddr_in { u_char sin_family; /* Address Family */ u_short sin_port; /* UDP or TCP Port# */ /* network byte ordered */ struct in_addr sin_addr; /* Internet Address */ char sin_zero[8]; /* unused */ }; Internet Addressing Data Structure โ€ข sin_family = AF_INET selects Internet address family
  • 18. Lecture 3: 9-4-01 18 Byte Ordering โ€ข Big Endian โ€ข Sun Solaris, PowerPC, ... โ€ข Little Endian โ€ข i386, alpha, ... โ€ข Network byte order = Big Endian 128 2 194 95 union { u_int32_t addr; /* 4 bytes address */ char c[4]; } un; /* 128.2.194.95 */ un.addr = 0x8002c25f; /* c[0] = ? */ c[0] c[1] c[2] c[3] 95 194 2 128
  • 19. Lecture 3: 9-4-01 19 Byte Ordering Functions โ€ข Converts between host byte order and network byte order โ€ข โ€˜hโ€™ = host byte order โ€ข โ€˜nโ€™ = network byte order โ€ข โ€˜lโ€™ = long (4 bytes), converts IP addresses โ€ข โ€˜sโ€™ = short (2 bytes), converts port numbers #include <netinet/in.h> unsigned long int htonl(unsigned long int hostlong); unsigned short int htons(unsigned short int hostshort); unsigned long int ntohl(unsigned long int netlong); unsigned short int ntohs(unsigned short int netshort);
  • 20. Lecture 3: 9-4-01 20 Lecture Overview โ€ข Application layer โ€ข Client-server โ€ข Application requirements โ€ข Background โ€ข TCP vs. UDP โ€ข Byte ordering โ€ข Socket I/O โ€ข TCP/UDP server and client โ€ข I/O multiplexing
  • 21. Lecture 3: 9-4-01 21 โ€ข A socket is a file descriptor that lets an application read/write data from/to the network โ€ข socket returns an integer (socket descriptor) โ€ข fd < 0 indicates that an error occurred โ€ข socket descriptors are similar to file descriptors โ€ข AF_INET: associates a socket with the Internet protocol family โ€ข SOCK_STREAM: selects the TCP protocol โ€ข SOCK_DGRAM: selects the UDP protocol What is a Socket? int fd; /* socket descriptor */ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) } perror(โ€œsocketโ€); exit(1); }
  • 22. Lecture 3: 9-4-01 22 TCP IP Ethernet Adapter Web Server Port 80 โ€ข For example: web server โ€ข What does a web server need to do so that a web client can connect to it? TCP Server
  • 23. Lecture 3: 9-4-01 23 โ€ข Since web traffic uses TCP, the web server must create a socket of type SOCK_STREAM int fd; /* socket descriptor */ if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror(โ€œsocketโ€); exit(1); } โ€ข socket returns an integer (socket descriptor) โ€ข fd < 0 indicates that an error occurred โ€ข AF_INET associates a socket with the Internet protocol family โ€ข SOCK_STREAM selects the TCP protocol Socket I/O: socket()
  • 24. Lecture 3: 9-4-01 24 โ€ข A socket can be bound to a port int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* create the socket */ srv.sin_family = AF_INET; /* use the Internet addr family */ srv.sin_port = htons(80); /* bind socket โ€˜fdโ€™ to port 80*/ /* bind: a client may connect to any of my addresses */ srv.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror("bind"); exit(1); } โ€ข Still not quite ready to communicate with a client... Socket I/O: bind()
  • 25. Lecture 3: 9-4-01 25 Socket I/O: listen() โ€ข listen indicates that the server will accept a connection int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* 1) create the socket */ /* 2) bind the socket to a port */ if(listen(fd, 5) < 0) { perror(โ€œlistenโ€); exit(1); } โ€ข Still not quite ready to communicate with a client...
  • 26. Lecture 3: 9-4-01 26 Socket I/O: accept() โ€ข accept blocks waiting for a connection int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ struct sockaddr_in cli; /* used by accept() */ int newfd; /* returned by accept() */ int cli_len = sizeof(cli); /* used by accept() */ /* 1) create the socket */ /* 2) bind the socket to a port */ /* 3) listen on the socket */ newfd = accept(fd, (struct sockaddr*) &cli, &cli_len); if(newfd < 0) { perror("accept"); exit(1); } โ€ข accept returns a new socket (newfd) with the same properties as the original socket (fd) โ€ข newfd < 0 indicates that an error occurred
  • 27. Lecture 3: 9-4-01 27 Socket I/O: accept() continued... struct sockaddr_in cli; /* used by accept() */ int newfd; /* returned by accept() */ int cli_len = sizeof(cli); /* used by accept() */ newfd = accept(fd, (struct sockaddr*) &cli, &cli_len); if(newfd < 0) { perror("accept"); exit(1); } โ€ข How does the server know which client it is? โ€ข cli.sin_addr.s_addr contains the clientโ€™s IP address โ€ข cli.sin_port contains the clientโ€™s port number โ€ข Now the server can exchange data with the client by using read and write on the descriptor newfd. โ€ข Why does accept need to return a new descriptor?
  • 28. Lecture 3: 9-4-01 28 Socket I/O: read() โ€ข read can be used with a socket โ€ข read blocks waiting for data from the client but does not guarantee that sizeof(buf) is read int fd; /* socket descriptor */ char buf[512]; /* used by read() */ int nbytes; /* used by read() */ /* 1) create the socket */ /* 2) bind the socket to a port */ /* 3) listen on the socket */ /* 4) accept the incoming connection */ if((nbytes = read(newfd, buf, sizeof(buf))) < 0) { perror(โ€œreadโ€); exit(1); }
  • 29. Lecture 3: 9-4-01 29 TCP IP Ethernet Adapter 2 Web Clients TCP Client โ€ข For example: web client โ€ข How does a web client connect to a web server?
  • 30. Lecture 3: 9-4-01 30 struct sockaddr_in srv; srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€); if(srv.sin_addr.s_addr == (in_addr_t) -1) { fprintf(stderr, "inet_addr failed!n"); exit(1); } Converting a numerical address to a string: Dealing with IP Addresses โ€ข IP Addresses are commonly written as strings (โ€œ128.2.35.50โ€), but programs deal with IP addresses as integers. struct sockaddr_in srv; char *t = inet_ntoa(srv.sin_addr); if(t == 0) { fprintf(stderr, โ€œinet_ntoa failed!nโ€); exit(1); } Converting strings to numerical address:
  • 31. Lecture 3: 9-4-01 31 Translating Names to Addresses โ€ข Gethostbyname provides interface to DNS โ€ข Additional useful calls โ€ข Gethostbyaddr โ€“ returns hostent given sockaddr_in โ€ข Getservbyname โ€ข Used to get service description (typically port number) โ€ข Returns servent based on name #include <netdb.h> struct hostent *hp; /*ptr to host info for remote*/ struct sockaddr_in peeraddr; char *name = โ€œwww.cs.cmu.eduโ€; peeraddr.sin_family = AF_INET; hp = gethostbyname(name) peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;
  • 32. Lecture 3: 9-4-01 32 Socket I/O: connect() โ€ข connect allows a client to connect to a server... int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by connect() */ /* create the socket */ /* connect: use the Internet address family */ srv.sin_family = AF_INET; /* connect: socket โ€˜fdโ€™ to port 80 */ srv.sin_port = htons(80); /* connect: connect to IP Address โ€œ128.2.35.50โ€ */ srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€); if(connect(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror(โ€connect"); exit(1); }
  • 33. Lecture 3: 9-4-01 33 Socket I/O: write() โ€ข write can be used with a socket int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by connect() */ char buf[512]; /* used by write() */ int nbytes; /* used by write() */ /* 1) create the socket */ /* 2) connect() to the server */ /* Example: A client could โ€œwriteโ€ a request to a server */ if((nbytes = write(fd, buf, sizeof(buf))) < 0) { perror(โ€œwriteโ€); exit(1); }
  • 34. Lecture 3: 9-4-01 34 Review: TCP Client-Server Interaction socket() bind() listen() accept() write() read() read() TCP Server close() socket() TCP Client connect() write() read() close() connection establishment data request data reply end-of-file notification from UNIX Network Programming Volume 1, figure 4.1
  • 35. Lecture 3: 9-4-01 35 UDP IP Ethernet Adapter NTP daemon UDP Server Example Port 123 โ€ข For example: NTP daemon โ€ข What does a UDP server need to do so that a UDP client can connect to it?
  • 36. Lecture 3: 9-4-01 36 Socket I/O: socket() โ€ข The UDP server must create a datagram socketโ€ฆ int fd; /* socket descriptor */ if((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror(โ€œsocketโ€); exit(1); } โ€ข socket returns an integer (socket descriptor) โ€ข fd < 0 indicates that an error occurred โ€ข AF_INET: associates a socket with the Internet protocol family โ€ข SOCK_DGRAM: selects the UDP protocol
  • 37. Lecture 3: 9-4-01 37 Socket I/O: bind() โ€ข A socket can be bound to a port int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ /* create the socket */ /* bind: use the Internet address family */ srv.sin_family = AF_INET; /* bind: socket โ€˜fdโ€™ to port 80*/ srv.sin_port = htons(80); /* bind: a client may connect to any of my addresses */ srv.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(fd, (struct sockaddr*) &srv, sizeof(srv)) < 0) { perror("bind"); exit(1); } โ€ข Now the UDP server is ready to accept packetsโ€ฆ
  • 38. Lecture 3: 9-4-01 38 Socket I/O: recvfrom() โ€ข read does not provide the clientโ€™s address to the UDP server int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by bind() */ struct sockaddr_in cli; /* used by recvfrom() */ char buf[512]; /* used by recvfrom() */ int cli_len = sizeof(cli); /* used by recvfrom() */ int nbytes; /* used by recvfrom() */ /* 1) create the socket */ /* 2) bind to the socket */ nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) &cli, &cli_len); if(nbytes < 0) { perror(โ€œrecvfromโ€); exit(1); }
  • 39. Lecture 3: 9-4-01 39 Socket I/O: recvfrom() continued... nbytes = recvfrom(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) cli, &cli_len); โ€ข The actions performed by recvfrom โ€ข returns the number of bytes read (nbytes) โ€ข copies nbytes of data into buf โ€ข returns the address of the client (cli) โ€ข returns the length of cli (cli_len) โ€ข donโ€™t worry about flags
  • 40. Lecture 3: 9-4-01 40 TCP IP Ethernet Adapter 2 UDP Clients UDP Client Example ports โ€ข How does a UDP client communicate with a UDP server?
  • 41. Lecture 3: 9-4-01 41 Socket I/O: sendto() โ€ข write is not allowed โ€ข Notice that the UDP client does not bind a port number โ€ข a port number is dynamically assigned when the first sendto is called int fd; /* socket descriptor */ struct sockaddr_in srv; /* used by sendto() */ /* 1) create the socket */ /* sendto: send data to IP Address โ€œ128.2.35.50โ€ port 80 */ srv.sin_family = AF_INET; srv.sin_port = htons(80); srv.sin_addr.s_addr = inet_addr(โ€œ128.2.35.50โ€); nbytes = sendto(fd, buf, sizeof(buf), 0 /* flags */, (struct sockaddr*) &srv, sizeof(srv)); if(nbytes < 0) { perror(โ€œsendtoโ€); exit(1); }
  • 42. Lecture 3: 9-4-01 42 Review: UDP Client-Server Interaction socket() bind() recvfrom() sendto() UDP Server socket() UDP Client sendto() recvfrom() close() blocks until datagram received from a client data request data reply from UNIX Network Programming Volume 1, figure 8.1
  • 43. Lecture 3: 9-4-01 43 UDP IP Ethernet Adapter UDP Server The UDP Server Port 2000 Port 3000 โ€ข How can the UDP server service multiple ports simultaneously?
  • 44. Lecture 3: 9-4-01 44 int s1; /* socket descriptor 1 */ int s2; /* socket descriptor 2 */ /* 1) create socket s1 */ /* 2) create socket s2 */ /* 3) bind s1 to port 2000 */ /* 4) bind s2 to port 3000 */ while(1) { recvfrom(s1, buf, sizeof(buf), ...); /* process buf */ recvfrom(s2, buf, sizeof(buf), ...); /* process buf */ } UDP Server: Servicing Two Ports โ€ข What problems does this code have?
  • 45. Lecture 3: 9-4-01 45 Socket I/O: select() int select(int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); FD_CLR(int fd, fd_set *fds); /* clear the bit for fd in fds */ FD_ISSET(int fd, fd_set *fds); /* is the bit for fd in fds? */ FD_SET(int fd, fd_set *fds); /* turn on the bit for fd in fds */ FD_ZERO(fd_set *fds); /* clear all bits in fds */ โ€ข maxfds: number of descriptors to be tested โ€ข descriptors (0, 1, ... maxfds-1) will be tested โ€ข readfds: a set of fds we want to check if data is available โ€ข returns a set of fds ready to read โ€ข if input argument is NULL, not interested in that condition โ€ข writefds: returns a set of fds ready to write โ€ข exceptfds: returns a set of fds with exception conditions
  • 46. Lecture 3: 9-4-01 46 Socket I/O: select() int select(int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); struct timeval { long tv_sec; /* seconds / long tv_usec; /* microseconds */ } โ€ข timeout โ€ข if NULL, wait forever and return only when one of the descriptors is ready for I/O โ€ข otherwise, wait up to a fixed amount of time specified by timeout โ€ข if we donโ€™t want to wait at all, create a timeout structure with timer value equal to 0 โ€ข Refer to the man page for more information
  • 47. Lecture 3: 9-4-01 47 int s1, s2; /* socket descriptors */ fd_set readfds; /* used by select() */ /* create and bind s1 and s2 */ while(1) { FD_ZERO(&readfds); /* initialize the fd set */ FD_SET(s1, &readfds); /* add s1 to the fd set */ FD_SET(s2, &readfds); /* add s2 to the fd set */ if(select(s2+1, &readfds, 0, 0, 0) < 0) { perror(โ€œselectโ€); exit(1); } if(FD_ISSET(s1, &readfds)) { recvfrom(s1, buf, sizeof(buf), ...); /* process buf */ } /* do the same for s2 */ } Socket I/O: select() โ€ข select allows synchronous I/O multiplexing
  • 48. Lecture 3: 9-4-01 48 TCP IP Ethernet Adapter Web Server Port 80 How can a a web server manage multiple connections simultaneously? Port 8001 More Details About a Web Server
  • 49. Lecture 3: 9-4-01 49 int fd, next=0; /* original socket */ int newfd[10]; /* new socket descriptors */ while(1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); /* Now use FD_SET to initialize other newfdโ€™s that have already been returned by accept() */ select(maxfd+1, &readfds, 0, 0, 0); if(FD_ISSET(fd, &readfds)) { newfd[next++] = accept(fd, ...); } /* do the following for each descriptor newfd[n] */ if(FD_ISSET(newfd[n], &readfds)) { read(newfd[n], buf, sizeof(buf)); /* process data */ } } Socket I/O: select() โ€ข Now the web server can support multiple connections...
  • 50. Lecture 3: 9-4-01 50 A Few Programming Notes: Representing Packets 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Length | Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Type: 4-byte integer Length: 2-byte integer Checksum: 2-byte integer Address: 4-byte IP address
  • 51. Lecture 3: 9-4-01 51 A Few Programming Notes: Building a Packet in a Buffer struct packet { u_int32_t type; u_int16_t length; u_int16_t checksum; u_int32_t address; }; /* ================================================== */ char buf[1024]; struct packet *pkt; pkt = (struct packet*) buf; pkt->type = htonl(1); pkt->length = htons(2); pkt->checksum = htons(3); pkt->address = htonl(4);
  • 52. Lecture 3: 9-4-01 52 Socket Programming References โ€ข Man page โ€ข usage: man <function name> โ€ข Textbook โ€ข Sections 2.6, 2.7 โ€ข demo programs written in Java โ€ข Unix Network Programming : Networking APIs: Sockets and XTI (Volume 1) โ€ข Section 2, 3, 4, 6, 8 โ€ข ultimate socket programming bible!