TCP UDP SOCKETS
TCP UDP SOCKETS
with
TCP/UDP Sockets
OSI Architecture
Physical Network
2 NP-MCA-SAEC 09-Jan-18
User and System
Programs
Kernel Support
Hardware
3 NP-MCA-SAEC 09-Jan-18
Networking Basics
Computers running on the
Internet communicate to each
other using either
TCP (Transmission Control application
application
Protocol) or application
presentation
presentation application sockets
UDP (User Datagram
session API
Protocol) session
When you write C programs transport TCP,
TCP,UDP,
UDP,…
…
transport
that communicate over the network
network
IPv4,
IPv4,IPv6
IPv6
network, you are data device
devicedriver
datalink
link driver
programming at the
physical &&hardware
hardware
application layer physical
Typically, you don’t need to Internet
OSI model
concern yourself with TCP protocol suite
and UDP layers
4 NP-MCA-SAEC 09-Jan-18
TCP
Definition
A connection-based protocol that provides a
reliable flow of data between two computers
e.g. if you want to speak to your aunt, a
connection is established when dial her number
and she answers
TCP guarantees that
data sent from one end of the connection
actually gets to the other end
and in the same order it was sent
(otherwise, and error is reported)
e.g.
HTTP, FTP, Telnet, etc.
5 NP-MCA-SAEC 09-Jan-18
TCP Connections
Host A Host B
131.181.7.22 128.10.2.3
1069 25
Process Process
1557
Process Process
80
Process Process
1111
6 NP-MCA-SAEC 09-Jan-18
TCP Header Format
Data
7 NP-MCA-SAEC 09-Jan-18
UDP
Definition
A protocol that sends independent packets of
data, called datagrams, from one computer to
another with no guarantees about arrival
e.g. sending a letter through the postal service
UDP is not connection-based like TCP
the order of delivery is not important and is not
guaranteed
each message is independent of any other
Why we use UDP?
Some forms of communication don’t require such
strict reliability
Reliable connection may require extra overhead
e.g.
NP-MCA-SAEC
8 Clock server and its clients, Ping, 09-Jan-18
UDP Datagram Format
Data
9 NP-MCA-SAEC 09-Jan-18
Comparing IP, UDP & TCP
IP - unreliable datagram delivery between
hosts.
UDP - unreliable datagram delivery
between processes (with minimal
overhead).
TCP - reliable, byte-stream delivery
between processes.
10 NP-MCA-SAEC 09-Jan-18
IP Protocol
0 15 16 31
Removed (6)
vers hlen TOS total length ID, Flags, frag offset
identification flags frag offset
20 TOS, hlen
bytes TTL protocol header checksum
source address
header checksum
destination address Changed: (3)
options and padding
total length=> payload
IPv4 protocol => next header
TTL=> hop limit
vers traffic class flow label
pay load length next header hop limit
Added: (2)
traffic class
40
bytes source address flow label
destination address
Expanded
address 32 bits to 128 bits
IPv6
11 NP-MCA-SAEC 09-Jan-18
Network Layer In The IPV4 Addresses
Internet
Address Classes
The Internet designers were unsure whether the world would evolve into a few networks with many hosts (e.g., large networks), or many
networks each supporting only a few hosts (e.g., small networks).
Thus, Internet addresses handle both large and small networks.
Internet address are four bytes in size, where:
12 NP-MCA-SAEC 09-Jan-18
TCP/IP Protocol Structure
UDP TCP
ICMP IGMP
IP ARP RARP
DATA LINK
NP-MCA-SAEC PHYSICAL
13 09-Jan-18
Client-Server Architecture
response
Client Server
request
14 NP-MCA-SAEC 09-Jan-18
Client/sever model Cont…
• Client asks (request) – server provides (response)
• Typically: single server - multiple clients
• The server does not need to know anything about the client
– even that it exists
• The client should always know something about the server
– at least where it is located
Server
Client
Connection socket pair (port 80)
(128.2.194.242:3479, 208.216.181.15:80)
17 NP-MCA-SAEC 09-Jan-18
Port
Definition
The TCP and UDP protocols use ports to map incoming data
to a particular process running on a computer
cf. IP address
used for delivering data to the right computer on the network
How does the computer know to which application to
forward the received data?
19 NP-MCA-SAEC 09-Jan-18
Ports
Each host has 65,536
Port 0
ports
Some ports are Port 1
20 NP-MCA-SAEC 09-Jan-18
Clients
• Examples of client programs
– Web browsers, ftp, telnet, ssh
• How does a client find the server?
– The IP address in the server socket address identifies the host
– The (well-known) port in the server socket address identifies the
service, and thus implicitly identifies the server process that performs
that service.
– Examples of well known ports
• Port 7: Echo server
• Port 23: Telnet server
• Port 25: Mail server
• Port 80: Web server
21 NP-MCA-SAEC 09-Jan-18
Using Ports to Identify Services
Server host 128.2.194.242
22 NP-MCA-SAEC 09-Jan-18
Servers
• Servers are long-running processes (daemons).
– Created at boot-time (typically) by the init process (process 1)
– Run continuously until the machine is turned off.
• Each server waits for requests to arrive on a well-known
port associated with a particular service.
– Port 7: echo server
– Port 23: telnet server See /etc/services for a
– Port 25: mail server comprehensive list of
the services available
– Port 80: HTTP server on a Linux machine.
• Other applications should choose between 1024 and 65535
23 NP-MCA-SAEC 09-Jan-18
Socket
Definition
One end-point of a two-way communication link
between two programs running on a network
A socket is bound to a specific port number so
that the TCP layer can identify the application
that data is destined to be sent
connection
port
Server
port
port
Client
Client Port Client
Client
connection
• The main distinction between regular file I/O and socket I/O is
how the application “opens” the socket descriptors.
25 NP-MCA-SAEC 09-Jan-18
What is a socket?
26 NP-MCA-SAEC 09-Jan-18
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
27 NP-MCA-SAEC 09-Jan-18
Two essential types of
sockets
SOCK_STREAM SOCK_DGRAM
a.k.a. TCP a.k.a. UDP
reliable delivery unreliable delivery
in-order guaranteed no order guarantees
connection-oriented no notion of “connection” –
bidirectional app indicates dest. for each
packet
can send or receive
App
3 2 App D1
1
socket Dest.
3 2
1
socket D2
D3
28 NP-MCA-SAEC Q: why have type 09-Jan-18
SOCK_DGRAM?
Simple Client-Server Example
response
Client Server
request
socket()
bind()
socket() listen()
Connection
connect() establishment accept()
send()
Data request recv()
30 NP-MCA-SAEC 09-Jan-18
#include’s
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(),
sendto(), and recvfrom() */
#include <arpa/inet.h> /* for sockaddr_in and
inet_addr() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
31 NP-MCA-SAEC 09-Jan-18
Socket Address Structure
Generic socket address structure
struct sockaddr
{
uint8_t sa_len; // length of structure
unsigned short sa_family; // address family
// PF_INET, PF_INET6, PF_UNIX,…
char sa_data[14]; // family-specific address info.
}
IPv4
struct socket address structure
sockaddr_in
{
uint8_t sa_len;
unsigned short sa_family; // PF_INET
32 NP-MCA-SAEC 09-Jan-18
Address and port byte-
ordering
Address and port are stored as integers
u_short sin_port; (16 bit)
in_addr sin_addr; (32 bit) struct in_addr {
u_long s_addr;
};
Problem:
different machines / OS’s use different word orderings
• little-endian: lower bytes first
• big-endian: higher bytes first
these machines may communicate with one another
over the network
Big-Endian
machine Little-Endian
! ! !
12.40.119.128
128.119.40.12 machine
NG
O
12 R11 40 12
12 11 40 12
W
33 NP-MCA-SAEC 09-Jan-18
8 9 8 9
Solution: Network Byte-
Ordering
Defs:
Host Byte-Ordering: the byte ordering used
by a host (big or little)
Network Byte-Ordering: the byte ordering
used by the network – always big-endian
Any words sent through the network
should be converted to Network Byte-Order
prior to transmission (and back to Host
Byte-Order once received)
Q: should the socket perform the
conversion automatically?
Q: Given big-endian machines don’t need
conversion routines and little-endian machines
34 do, how do we avoid writing two versions of 09-Jan-18
NP-MCA-SAEC
code?
Byte Ordering Solution
There are two solutions if computers with different byte ordering
system want to communicate
They must know the kind of architecture of the sending computer
(bad solution, it has not been implemented)
Introduction of a network byte order. The functions are:
35 NP-MCA-SAEC 09-Jan-18
UNIX’s byte-ordering funcs
u_long ntohl(u_long x);
u_long htonl(u_long x); u_short ntohs(u_short x);
u_short htons(u_short x);
ntohl
hto
12 11 40 12 12 11 40 12
8 9 8 9
36 Same
NP-MCA-SAEC
code would have worked regardless of 09-Jan-18
Network Byte Ordering
Network is big-endian, host may be big- or little-endian
– Functions work on 16-bit (short) and 32-bit (long) values
– htons() / htonl() : convert host byte order to network byte order
– ntohs() / ntohl(): convert network byte order to host byte order
– Use these to convert network addresses, ports, …
37 NP-MCA-SAEC 09-Jan-18
Byte Manipulation Functions
Berkeley-derived functions
ANSI C
38 NP-MCA-SAEC 09-Jan-18
Functions
Convert IPv4 address
Between a dotted-decimal string and its 32-bit
network byte ordered binary value
39 NP-MCA-SAEC 09-Jan-18
TCP Sockets
bind()
bind() socket()
socket()
listen()
listen() TCP
TCP
Client Server
socket() accept()
accept()
socket()
connection established blocks until connection
connect() from client
connect() (TCP three-way handshake)
data (request)
write()
write() read()
read()
process request
end-of-file notification
close()
close() read()
read() close()
close()
40 NP-MCA-SAEC 09-Jan-18
Client+server: connection-oriented
BIND
SOCKET
LISTEN
CONNECT
SEND RECEIVE
SEND
RECEIVE
CLOSE
42 NP-MCA-SAEC 09-Jan-18
Example: Client Programming
43 NP-MCA-SAEC 09-Jan-18
Socket() Function
Definition
44 NP-MCA-SAEC 09-Jan-18
connect()
#include <sys/socket.h>
int connect( int sockfd, const struct sockaddr * servaddr, socklen_t
addrlen );
Returns: 0 if OK, -1 on error
e.g. connect()
struct sockaddr_in servaddr;
...
servaddr.sin_family = PF_INET;
servaddr.sin_addr.s_addr = htonl( “220.95.133.100” );
servaddr.sin_port = htons( 7 ); // 7 for echo service
45 NP-MCA-SAEC 09-Jan-18
bind()
#include <sys/socket.h>
int bind( int sockfd, const struct sockaddr * myaddr, socklen_t
addrlen );
Returns: 0 if OK, -1 on error
Process specifies
Result
IP address Port
Wildcard 0 Kernel chooses IP address and port
Wildcard Non-zero Kernel chooses IP address, process specifies port
e.g. bind()
myaddr.sin_family = PF_INET;
myaddr.sin_addr.s_addr = htonl( INADDR_ANY );
myaddr.sin_port = htons( 7 ); // 7 for echo service
if( bind( sockfd, (struct sockaddr *)&myaddr,
sizeof(myaddr) ) < 0 ) { ... }
46 NP-MCA-SAEC 09-Jan-18
listen() and accept()
#include <sys/socket.h>
int listen( int sockfd, int backlog );
Returns: 0 if OK, -1 on error
e.g. listen()
#define LISTENQ 5
...
if( listen( mysock, LISTENQ ) < 0 ) { ... }
while( 1 ){
clilen = sizeof( cliaddr );
if( ( clisockfd = accept( mysock, (struct sockaddr *)&cliaddr,
&clilen ) ) < 0 ) { ... }
...
}
47 NP-MCA-SAEC 09-Jan-18
recv() and send()
#include <sys/types.h>
#include <sys/socket.h>
int recv( int sockfd, void * buff, size_t len, int flags );
int send( int sockfd, const void * buff, size_t len, int flags );
Both return: number of bytes read or written if OK, -1 on error
48 NP-MCA-SAEC 09-Jan-18
Basic TCP Socket I/O
Read()
# include <unistd.h>
int read(int sockfd, char *ptr, size_t nbytes);
Returns: number of bytes read, -1 on
error
Write()
# include <unistd.h>
int write(int sockfd, char *ptr, size_t nbytes);
Returns: number of bytes written, -1 on
error
49 NP-MCA-SAEC 09-Jan-18
Close() Function
Definition
50 NP-MCA-SAEC 09-Jan-18
Server Example
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void) {
int sockfd, new_fd; // listen on sockfd, new connection on new_fd
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector's address information
int sin_size;
51 NP-MCA-SAEC 09-Jan-18
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
52 NP-MCA-SAEC 09-Jan-18
Client Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s",buf);
close(sockfd);
return 0;
}
54 NP-MCA-SAEC 09-Jan-18
UDP Sockets
socket()
socket()
bind()
bind() UDP
UDP Server
Client recvfrom()
recvfrom()
socket()
socket()
blocks until datagram
data (request) received from client
sendto()
sendto()
process request
data (reply)
sendto()
sendto()
recvfrom()
recvfrom()
close()
close()
55 NP-MCA-SAEC 09-Jan-18
Client+server: connectionless
CREATE
BIND
RECEIVE
SEND
CLOSE
56 NP-MCA-SAEC 09-Jan-18
recvfrom() and sendto()
#include <sys/socket.h>
ssize_t recvfrom( int sockfd, void * buff, size_t nbytes, int flags,
struct sockaddr * from, socklen_t * addrlen );
ssize_t sendto( int sockfd, const void * buff, size_t nbytes, int
flags, const struct sockaddr * to, socklen_t addrlen )
Both return: number of bytes read or written if OK, -1 on error
e.g. recvfrom() and sendto()
recvfrom()
# include <sys/socket.h>
int recvfrom(int s, void *buf, int len, unsigned int flags,
struct sockaddr *from, int *fromlen);
Returns: number of bytes received, -1 on
58 error
NP-MCA-SAEC 09-Jan-18
Server: Alternative Ways of
Handling Many Clients
59 NP-MCA-SAEC 09-Jan-18
Compile & Run
Compile
Server
$sand>gcc server.c –o server
$rain>gcc client.c –o client
Run
Server
$sand>./server
Client
$rain>./client sand.cise.ufl.edu
60 NP-MCA-SAEC 09-Jan-18
Concurrent vs. Iterative
An iterative server handles a single client
request at one time.
A concurrent server can handle multiple
client requests at one time.
61 NP-MCA-SAEC 09-Jan-18
Concurrent vs. Iterative
Concurrent
•Large or variable size requests
•Harder to program
•Typically uses more system resources
Iterative
•Small, fixed size requests
•Easy to program
Connectionless vs.
Connection-Oriented
Connection-Oriented
•EASY TO PROGRAM
•transport protocol handles the tough stuff.
•requires separate socket for each connection.
Connectionless
•less overhead
•no limitation on number of clients
63 NP-MCA-SAEC 09-Jan-18
Per-Client Process
e.g. fork()
...
while( 1 )
{
clilen = sizeof( cliaddr );
if( ( clisockfd = accept( mysock, (struct sockaddr
*)&cliaddr,
&clilen ) ) < 0 ) { ... }
64 NP-MCA-SAEC 09-Jan-18
END