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

TCP UDP SOCKETS

The document provides an overview of network programming using TCP and UDP sockets, detailing the OSI architecture and the roles of different protocols. It explains the characteristics of TCP as a reliable, connection-based protocol and UDP as a connectionless protocol with no delivery guarantees. Additionally, it covers socket types, port numbers, and the client-server architecture, emphasizing the importance of sockets in facilitating communication between applications over a network.

Uploaded by

dineshraju3435
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

TCP UDP SOCKETS

The document provides an overview of network programming using TCP and UDP sockets, detailing the OSI architecture and the roles of different protocols. It explains the characteristics of TCP as a reliable, connection-based protocol and UDP as a connectionless protocol with no delivery guarantees. Additionally, it covers socket types, port numbers, and the client-server architecture, emphasizing the importance of sockets in facilitating communication between applications over a network.

Uploaded by

dineshraju3435
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

NETWORK PROGRAMMING

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

1 byte 1 byte 1 byte 1 byte


Source Port Destination Port
Sequence Number
Acknowledgement Number
Hlength Reserved Control Window
Checksum Urgent Pointer
Options & Padding (if any)

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

1 byte 1 byte 1 byte 1 byte


Source Port Destination Port
Total Length Checksum

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:

 Class A addresses start with a `0' in the most significant


bit, followed by a 7-bit network address and a 24-bit local
part.

 Class B addresses start with a `10' in the two most


significant bits, followed by a 14-bit network number and a
16-bit local part.

 Class C addresses start with a `110' in the three most


significant bits, followed by a 21-bit network number and
an 8-bit local part.

 Class D addresses start with a `1110' in the four most


significant bits, followed by a 28-bit group number. Used
for multicast.

 Class E addresses start with a ‘11110’ and are reserved for


future use.

12 NP-MCA-SAEC 09-Jan-18
TCP/IP Protocol Structure

SMTP FTP Telnet DNS SNMP HTTP

UDP TCP

ICMP IGMP
IP ARP RARP

DATA LINK

NP-MCA-SAEC PHYSICAL
13 09-Jan-18
Client-Server Architecture

response

Client Server
request

Client requests service from server


Server responds with sending service or error
message to client

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

1. Client sends request


Client Server
process process Resource
4. Client 3. Server sends response 2. Server
handles handles
response request

Note: clients and servers are processes running on hosts


15 NP-MCA-SAEC 09-Jan-18
(can be the same or different hosts).
Internet Connections (TCP/IP)
• Address the machine on the network
– By IP address
• Address the process
– By the “port”-number
• The pair of IP-address + port – makes up a “socket-address”
Server socket
Client socket address
address
128.2.194.242:3479
208.216.181.15:80

Server
Client
Connection socket pair (port 80)
(128.2.194.242:3479, 208.216.181.15:80)

Client host address Server host address


128.2.194.242 208.216.181.15

Note: 3479 is an Note: 80 is a well-known port


ephemeral port allocated
NP-MCA-SAEC associated with Web servers
16 09-Jan-18
by the kernel
Addresses, Ports and Sockets
 Like apartments and mailboxes
You are the application
Your apartment building address is the address
Your mailbox is the port
The post-office is the network
The socket is the key that gives you access to the right mailbox
(one difference: assume outgoing mail is placed by you in your
mailbox)

Q: How do you choose which port a socket connects to?

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?

0~1024: reserved for


well-known services

app app app app


0~65,535

port port port port


TCP
TCPororUDP
UDP packet
18 NP-MCA-SAEC port # data 09-Jan-18
Port numbers
16-bit integer
Differentiate a socket-related process from
another
Ranges
Well-known ports (0 ~1023): assigned by
IANA
e.g.) FTP (21), web server (80), …
Registered ports (1024 ~ 49151):
recommendation list
e.g.) X Window server (6000 ~ 6003)
Dynamic or private ports (49152 ~ 65535)

19 NP-MCA-SAEC 09-Jan-18
Ports
Each host has 65,536
Port 0
ports
Some ports are Port 1

reserved for specific


apps Port 65535
20,21: FTP
23: Telnet  A socket provides an
80: HTTP interface to send data
to/from the network through
see RFC 1700 (about
a port
2000 ports are
reserved)

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

Client host Service request for Web server


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

Service request for Web server


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

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

Server request Server


Server

port
Client
Client Port Client
Client
connection

The client and server can communicate by


writing to or reading from their sockets
similar to file descriptor
24 NP-MCA-SAEC 09-Jan-18
Sockets
• What is a socket?
– To the kernel, a socket is an endpoint of communication.
– To an application, a socket is a file descriptor that lets the application
read/write from/to the network.
• Remember: All Unix I/O devices, including networks, are modeled as
files.

• Clients and servers communicate with each by reading from


and writing to socket descriptors.

• 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?

An interface between application and


network
The application creates a socket
The socket type dictates the style of
communication
reliable vs. best effort
connection-oriented vs. connectionless
Once configured the application can
pass data to the socket for network
transmission
receive data from the socket (transmitted
through the network by some other host)

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()

Data response send()


recv()
close() recv()
End-of-file notification
29 NP-MCA-SAEC close() 09-Jan-18
Header Files
<sys/types.h> - prerequisite typedefs
<errno.h>- names for “errorno” values
<sys/socket.h> - struct socket addr; sys
prototypes and constants.
<netdb.h> - N/w info lookup prototypes
<netinet/in.h> - struct sockaddr_in; byte
ordering macros
<arpa/inet.h> - utility function prototypes

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

#define MAX 255 /* Longest string to echo */

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

in_port_t sin_port; // 16-bit TCP or UDP port number


struct in_addr sin_addr; // 32-bit IPv4 address
char sin_zero[8]; // unused
}

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:

 uint16_t htons(uint16_t host16bitvalue)


 uint32_t htonl(uint32_t host32bitvalue)
 uint16_t ntohs(uint16_t net16bitvalue)
 uint32_t ntohl(uint32_t net32bitvalue)
 Note: use for all integers (short and long), which are sent across
the network
Including port numbers and IP addresses

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

 On big-endian machines, these routines do


nothing
 On little-endian machines, they reverse the
Big-Endian
byte order Little-Endian12 128.119.40.12
12 11 40
128.119.40.12 machine
12 40 11 12
8 9 machine 9 8
nl

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

struct sockaddr_in serveraddr;


/* fill in serveraddr with an address */

/* Connect takes (struct sockaddr *) as its second argument */
connect(clientfd, (struct sockaddr *) &serveraddr,
sizeof(serveraddr));

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

data (reply) write()


read()
read() write()

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

TCP three-way ACCEPT


handshake

SEND RECEIVE

SEND
RECEIVE

CLOSE

41 NP-MCA-SAEC Concurrent server 09-Jan-18


Example: Server Programming
 create stream socket (socket() )
 Bind port to socket (bind() )
 Listen for new client (listen() )
 While
Wait for (select() )
 (depending on which file descriptors are ready)
accept user connection and create a new socket (accept() )
data arrives from client (recv() )
data has to be send to client (send() )

42 NP-MCA-SAEC 09-Jan-18
Example: Client Programming

Create stream socket (socket() )


Connect to server (connect() )
While still connected:
send message to server (send() )
receive (recv() ) data from server and
process it
Close TCP connection and Socket (close())

43 NP-MCA-SAEC 09-Jan-18
Socket() Function
Definition

Protocol family constants & Socket type

Protocol argument is normally set to 0 except for raw socket

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

if( connect( sockfd, (struct sockaddr *)&servaddr,


sizeof(servaddr) ) < 0 )
{ ... }
...

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

Local IP address 0 Process specifies IP address and kernel chooses port

Local IP address Non-zero Process specifies IP address and 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

int accept( int sockfd, struct sockaddr * cliaddr, socklen_t *


addrlen )
Returns: non-negative descriptor 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

 e.g. send() and recv()

 if( ( n = send( sockfd, buff, len, 0 ) ) != len ){ ... }


...
if( ( n = recv( sockfd, buff, BUFMAX, 0 ) ) < 0 ) { ... }

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>

 #define MYPORT 3490 // the port users will be connecting to


 #define BACKLOG 10 // how many pending connections queue will hold

 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;

 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket");


 exit(1);
 }

 my_addr.sin_family = AF_INET; // host byte order


 my_addr.sin_port = htons(MYPORT); // short, network byte order
 my_addr.sin_addr.s_addr = INADDR_ANY; // auto. filled with local IP
 memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct

51 NP-MCA-SAEC 09-Jan-18
 if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
 perror("bind");
 exit(1);
 }

 if (listen(sockfd, BACKLOG) == -1) {


 perror("listen");
 exit(1);
 }

 while(1) { // main accept() loop
 sin_size = sizeof(struct sockaddr_in);
 if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
 perror("accept");
 continue;
 }

 printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));

 if (send(new_fd, "Hello, world!\n", 14, 0) == -1)


 perror("send");

 close(new_fd);
 }
 return 0;
 }

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>

#define PORT 3490 // the port client will be connecting to


#define MAXDATASIZE 100 // max number of bytes we can get
// at once
int main(int argc, char *argv[]) {
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr; // server's address information

if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}

if ((he=gethostbyname(argv[1])) == NULL) { // get the host info


perror("gethostbyname");
exit(1);
}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {


perror("socket");
exit(1);
53 NP-MCA-SAEC
} 09-Jan-18
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(PORT); // short, network byte order
their_addr.sin_addr = *(struct in_addr *)*he->h_addr_list; // already network
byte order
memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct

if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))


== -1){
perror("connect");
exit(1);
}

if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {


perror("recv");
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()

 #define MAXLINE 255


char mesg[ MAXLINE ];
...
while( 1 )
{
if( ( n = recvfrom( sockfd, mesg, MAXLINE, 0, cliaddr, &len ) )
< 0 ) { ... }
sendto( sockfd, mesg, n, 0, cliaddr, len );
...
}
57 NP-MCA-SAEC 09-Jan-18
Basic UDP Socket I/O (1)
sendto()
# include <sys/socket.h>
int sendto(int s, const void *msg, int len, unsigned int flags,
const struct sockaddr *to, int tolen);
Returns: number of bytes sent, -1 on
error

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

Forking a new process for each client: fork()


But, creating new process is expensive.
Multithreaded implementation: have one
thread handling each client.
Thread is like a process but light-weighted.

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 ) { ... }

// fork child process


if( ( pid = fork() ) < 0 ) { ... }
else if( pid == 0 ) // child process
{
close( mysock );
HANDLE_REQUEST( clisockfd );
exit( 0 );
}
// parent process
...
}

64 NP-MCA-SAEC 09-Jan-18
END

You might also like