0% found this document useful (0 votes)
68 views

CS 468 Secure Programming and Systems Fall 2021: How To Develop Network Applications?

This lecture discusses network application development using socket programming. It introduces the client-server model as a common paradigm for network applications. Key points covered include how applications interact with the network stack via APIs, the roles of clients and servers, and the layered structure of network protocols. The document provides an overview of concepts relevant to writing programs that communicate over networks.

Uploaded by

lbms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

CS 468 Secure Programming and Systems Fall 2021: How To Develop Network Applications?

This lecture discusses network application development using socket programming. It introduces the client-server model as a common paradigm for network applications. Key points covered include how applications interact with the network stack via APIs, the roles of clients and servers, and the layered structure of network protocols. The document provides an overview of concepts relevant to writing programs that communicate over networks.

Uploaded by

lbms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

CS 468

Secure Programming and Systems


Fall 2021
Lecture #7
Network Application Development
Socket Programming

How to Develop Network Applications?


• How can we use the network functionalities (IP,
TCP/UDP) implemented by the OS?
– What are the gaps?
– TCP/IP specification does NOT include API
• How does the network application interact with the
network functionalities provided by the OS?
• How do network applications interact with each
other across the network?
– What messages are supposed to be exchanged among the
network applications?
– How to interpret the messages?
• Concurrency, error handling issues
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 2
Wang

1
Layers in Network Application
• Application
– Read data from and write data to the socket
– Interpret the data (e.g., render a Web page)
• Operating system
– Deliver data to the destination socket
– Based on the destination port number (e.g., 80)
• Network
– Deliver data packet to the destination host
– Based on the destination IP address
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 3
Wang

Network & Application


• Network
– transfers bits
– operates at application’s request
• Application determines
– what/when/where to send
– Meaning of bits
=> Application programs are the entities that
communicate with each other, not the computers or
users.

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 4
Wang

2
Network Applications and Application-
Layer Protocols
• Application: communicating,
distributed processes
application
– Running in network hosts in transport
network
“user space” data link
physical
– Exchange messages to
implement app
– e.g., email, file transfer, the Web
• Application-layer protocols
– One “piece” of an app
– Define messages exchanged by
application
apps and actions taken application transport
transport network
– Use services provided by lower network
data link
data link
physical
layer protocols physical

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 5
Wang

Generic Questions about Networking


Applications
• How do different network entities communicate?
– Someone has to be the first to initiate conversation!
– Who initiate communication?
• What mechanisms are available for a programmer
who writes network applications?
• How to write a network application that sends
packets between hosts across an IP network?

IP Network
X Y
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 6
Wang

3
Client-Server Paradigm
• Client program • Server program
– Running on end host – Running on end host
– Requests service – Provides service
(speaks first) – E.g., Web server
– E.g., Web browser
GET /index.html

“Site under construction”


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 7
Wang

Client-Server Communication
• Client “sometimes on” • Server is “always on”
– Starts later than server – Starts first, passively
– Initiates a request to the waiting for requests.
server when interested – Handles services requests
– Doesn’t communicate from many client hosts
directly with other clients – Doesn’t initiate contact
– Needs to know server’s with the clients
address – Needs fixed, known
address
request

response
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 8
Wang

4
Characteristics of a Client
• Arbitrary application program
• Becomes client temporarily
• Can also perform other computations
• Invoked directly by user
• Runs locally on user’s computer
• Actively initiates contact with a server
• A client can be a server at the same time!

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 9
Wang

Characteristics of a Server
• Special-purpose, privileged program
• Dedicated to providing one service
• Can handle multiple remote clients simultaneously
• Invoked automatically when system boots
• Executes forever
• Needs powerful computer and operating system
• Waits passively for client contact
• Accepts requests from arbitrary clients
• A server can be a client of another server at the
same time!
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 10
Wang

5
Layers of the IP Protocol Suite
e.g. ftp Application Layer
Application Layer

e.g. TCP, UDP


Transport Layer Transport Layer

e.g. IP
Network Layer Network Layer

Link Layer
Ethernet Link Layer

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 11
Wang

Protocol Suite Location

Application Layer
Applications
(e.g. browser, game, ftp)

Application Programming
Interface (API)
Transport Layer (TCP, UDP) (e.g. network API)

Operating System
(e.g. Unix)
Network Layer (IP)

Interface to the Network Card

Network Card &


Device Driver
Link Layer (e.g. Ethernet card)
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 12
Wang

6
Network Application Programming
Interface (API)
• The interface between application and protocol
software (often by the operating system).

Application
Network API
Protocol A Protocol B Protocol C

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 13
Wang

Desirable Properties of Network API


• Generic Programming Interface
– Support multiple communication protocol suites (families).
– Address (endpoint) representation independence.
– Provide special services for Client and Server?

• Support for message oriented and connection


oriented communication
• Work with existing I/O services (when this makes
sense)
• Operating System independence

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 14
Wang

7
API for Programming TCP/IP Applications
• TCP/IP does not include an API definition.
• There are a variety of APIs for use with
TCP/IP:
– Sockets
– TLI, XTI
– Winsock
– MacTCP

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 15
Wang

Network API Functions


• Specify local and remote communication
endpoints
• Initiate a connection
• Wait for incoming connection
• Send and receive data
• Terminate a connection gracefully
• Error handling

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 16
Wang

8
Berkeley Socket
• A socket is an abstract representation of a
communication endpoint.
– support for multiple protocol families.
– address representation independence
• Sockets work with Unix I/O services just like
files, pipes & FIFOs.
• Uses existing I/O programming interface as
much as possible.
• Sockets (obviously) have special needs:
– establishing a connection
– specifying communication endpoint addresses
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 17
Wang

Berkeley Socket
• Originally developed as part of BSD Unix
– BSD = Berkeley Software Distribution
– API=Application Program Interface
• Now the most popular API for C/C++
programmers writing applications over
TCP/IP
– Also supported in other languages
• Perl, Tcl/Tk, etc.
– Supported on other operating systems
• Mac
• Windows
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 18
Wang

9
Berkeley Socket Interface Internet

• The basic ideas:


– a socket is like a file:
• you can read/write from/to the network just like you
would a file
– For connection-oriented communication (e.g. TCP)
• servers (passive open) do listen and accept operations
• clients (active open) do connect operations
• both sides can then do read and/or write (or send and
recv)
• then each side must close
• There are more details, but those are the most important
ideas
– Connectionless (e.g. UDP): uses sendto and recvfrom
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 19
Wang

Socket and Process Communication

application layer application layer

User Process Internet User Process


Socket Socket
transport transport layer (TCP/UDP)
OS layer (TCP/UDP)
network OS network
network layer (IP)
Internet network layer (IP)
stack stack
link layer (e.g. ethernet) Internet link layer (e.g. ethernet)

The interface that the OS provides to its networking subsystem

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 20
Wang

10
Types of Internet Sockets
• Different types of sockets implement different communication
types (stream vs. datagram)
• Type of socket: stream socket
– connection-oriented
– two way communication
– reliable (error free), in order delivery
– can use the Transmission Control Protocol (TCP)
– e.g. telnet, ssh, http
• Type of socket: datagram socket
– connectionless, does not maintain an open connection, each packet is
independent
– can use the User Datagram Protocol (UDP)
– e.g. IP telephony
• Other types exist: similar to the one above
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 21
Wang

User Datagram Protocol (UDP):


Datagram Socket
UDP Postal Mail
• Single socket to receive messages •• Single
Single mailbox
mailboxto receive letters
to receive
messages
• No guarantee of delivery •• Unreliable
Unreliable ☺

• Not necessarily in-order delivery


•• Not necessarily in-order
Not necessarily in-order delivery
delivery
• Datagram – independent packets •• Each
Lettersletter is independent
sent independently
• Must address each reply
• Must address each packet • Must address each mail

Example UDP applications


Multimedia, voice over IP (Skype)
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 22
Wang

11
Transmission Control Protocol (TCP):
Stream Socket
TCP Telephone
Postal Mail
Call
• Reliable – guarantee delivery •• Single
Guaranteed delivery
mailbox to receive
messages
• Byte stream – in-order delivery •• Unreliable
In-order delivery

• Connection-oriented – single
•• Not necessarily in-order
Connection-oriented
socket per connection delivery
• Each letter is independent
• Setup connection followed by • Must address each
Setup connection reply
followed by
data transfer conversation

Example TCP applications


Web, Email, Telnet
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 23
Wang

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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 24
Wang

12
Socket Identification
• Communication Protocol
– TCP (Stream Socket): streaming, reliable
– UDP (Datagram Socket): packets, best effort
• Receiving host
– Destination address that uniquely identifies the host
– An IP address is a 32-bit quantity
• Receiving socket
– Host may be running many different processes
– Destination port that uniquely identifies the socket
– A port number is a 16-bit quantity
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 25
Wang

Socket Identification (Cont.)

Process Process
A B
port X port Y Port Number

TCP/UDP Protocol

Host Address
IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 26
Wang

13
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
• Well-known vs. ephemeral ports
– Server has a well-known port (e.g., port 80)
• Between 0 and 1023 (requires root to use)
– Client picks an unused ephemeral (i.e., temporary) port
• Between 1024 and 65535
• Uniquely identifying traffic between the hosts
– Two IP addresses and two port numbers
– Underlying transport protocol (e.g., TCP or UDP)
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 27
Wang

Using Ports to Identify Services


Server host 128.2.194.242
Service request for
Client host
128.2.194.242:80 Web server
(i.e., the Web server) (port 80)
Client OS
Echo server
(port 7)

Service request for


128.2.194.242:7 Web server
(i.e., the echo server) (port 80)
Client OS
Echo server
(port 7)

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 28
Wang

14
Typical Client-Server Interaction
response
Client Server
request
socket()
bind()
socket() listen()
Connection
connect() establishment accept()
send()
Data request recv()

Data response send()


recv()
close() recv()
End-of-file notification
close()
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 29
Wang

Internet Addressing Data Structure

#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 */
};

• sin_family = AF_INET selects Internet address family


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 30
Wang

15
Byte Ordering

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]

• Big Endian 128 2 194 95


– Sun Solaris, PowerPC, ...
• Little Endian 95 194 2 128
– i386, alpha, ...
• Network byte order = Big Endian
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 31
Wang

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);
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 32
Wang

16
Creating a Socket
int socket(int family,int type,int proto);

• family specifies the protocol family (PF_INET for


TCP/IP).
• type specifies the type of service
(SOCK_STREAM, SOCK_DGRAM).
• protocol specifies the specific protocol (usually 0,
which means the default).
• socket returns an integer (socket descriptor)
– fd < 0 indicates that an error occurred
– socket descriptors are similar to file descriptors
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 33
Wang

TCP Server

• For example: web server


Web Server

Port 80 • What does a web server


need to do so that a web
TCP client can connect to it?

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 34
Wang

17
Socket I/O: socket()
• 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
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 35
Wang

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 */

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...


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 36
Wang

18
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...

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 37
Wang

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
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 38
Wang

19
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?
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 39
Wang

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);
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 40
Wang

20
TCP Client
• For example: web client
• How does a web client 2 Web Clients

connect to a web server?

TCP

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 41
Wang

Dealing with IP Addresses


• IP Addresses are commonly written as strings (“128.2.35.50”),
but programs deal with IP addresses as integers.
Converting strings to numerical address:
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:


struct sockaddr_in srv;
char *t = inet_ntoa(srv.sin_addr);
if(t == 0) {
fprintf(stderr, “inet_ntoa failed!\n”); exit(1);
}
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 42
Wang

21
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.gmu.edu”;

peeraddr.sin_family = AF_INET;
hp = gethostbyname(name)
peeraddr.sin_addr.s_addr = ((struct in_addr*)(hp->h_addr))->s_addr;

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 43
Wang

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);
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 44
Wang

22
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);
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 45
Wang

Review: TCP Client-Server Interaction


TCP Server
socket()

bind()

TCP Client listen()


socket() accept()
connection establishment
connect()
data request read()
write()

data reply write()


read()

close() end-of-file notification read()

close()
By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 46
Wang

23
UDP Server Example

• For example: NTP daemon


NTP
daemon • What does a UDP server
Port 123 need to do so that a UDP
client can connect to it?
UDP

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 47
Wang

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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 48
Wang

24
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…


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 49
Wang

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);
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 50
Wang

25
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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 51
Wang

UDP Client Example

2 UDP Clients

• How does a UDP client


communicate with a UDP
server? ports
UDP

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 52
Wang

26
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);
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 53
Wang

Review: UDP Client-Server Interaction

UDP Server
socket()

bind()
UDP Client
recvfrom()
socket()
blocks until datagram
sendto() received from a client
data request

data reply sendto()


recvfrom()

close()

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 54
Wang

27
The UDP Server

• How can the UDP server


UDP Server service multiple ports
Port 3000 Port 2000 simultaneously?

UDP

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 55
Wang

UDP Server: Servicing Two Ports


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 */
}

• What problems does this code have?


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 56
Wang

28
Server Handling Concurrently Clients
• Multiple processes
– Forking a new process for each client: fork()
– Simple, but creating new process is expensive.
• Multiple threads
– Create a new thread for each client
– Light weight and more efficient than multi-process
approach.

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 57
Wang

Handling Concurrently Clients via I/O


Multiplexing: select()
• Waits on multiple file descriptors and timeout
• Returns when any file descriptor
– is ready to be read or
– written or
– indicate an error, or
– timeout exceeded
• Advantages
– One thread, more efficient
– Application does not consume CPU cycles while waiting
• Disadvantages
– does not scale to large number of file descriptors

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 58
Wang

29
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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 59
Wang

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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 60
Wang

30
Socket I/O: select()
• select allows synchronous I/O multiplexing
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 */
}

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 61
Wang

More Details About a Web Server

How can a a web server manage


multiple connections simultaneously?
Web Server

Port 8001 Port 80

TCP

IP

Ethernet Adapter

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 62
Wang

31
Socket I/O: select()
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 */
}
}

• Now the web server can support multiple connections...


By Dr. Xinyuan (Frank)
CS at George Mason University CS 468 Fall 2021 63
Wang

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

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 64
Wang

32
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);

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 65
Wang

Network Programmer’s Mistakes


• byte ordering
• separating records in streams
• use of select()
• misinterpreting the project specification

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 66
Wang

33
Socket Programming References
• Man page
– usage: man <function name>
• Internetworking with TCP/IP Volume III
• Unix Network Programming : Networking
APIs: Sockets and XTI (Volume 1)

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 67
Wang

HW3: Implementing a primitive


authenticated remote shell client and server

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 68
Wang

34
HW3: Implementing a primitive
authenticated remote shell client and server

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 69
Wang

HW3: Implementation Hints


• Where to modify SimpleRShellClient.c?
– Function int RemoteShell(char *destination, int portN)
– Add
• Constructing and sending client messages
• Handling received server messages
• Where to modify SimpleRShellServer.c?
– Function int RemoteShellD(int sock)
– Add
• Constructing and sending server messages
• Handling received client messages
• You want to have sanity test of any received message
to make sure it is legitimate

By Dr. Xinyuan (Frank)


CS at George Mason University CS 468 Fall 2021 70
Wang

35

You might also like