ClientServer Programming Using BSD Sockets - PowerPoint PPT Presentation

1 / 57
About This Presentation
Title:

ClientServer Programming Using BSD Sockets

Description:

if (argc 2) port = atoi(argv[2]); else port = PROTOPORT; ... fprintf (stderr, 'bad port number %s/n',argv[1]); exit (1); Example Server ... – PowerPoint PPT presentation

Number of Views:167
Avg rating:3.0/5.0
Slides: 58
Provided by: aap80
Learn more at: http://www.csce.uark.edu
Category:

less

Transcript and Presenter's Notes

Title: ClientServer Programming Using BSD Sockets


1
Client/Server ProgrammingUsing BSD Sockets
Short Presentation by Amy Apon
2
Client/Server ProgrammingOutline
  • What is a socket and what are the two types?
  • The layered network model
  • Client/server model and types of servers
  • Internet addressing
  • Basic socket calls
  • Sample client and server

3
What is a socket?
  • A way to communicate to other programs using a
    descriptor that is like a file descriptor. You
    must
  • open it
  • read/write or send/recv
  • close it

Sockets
4
Two Types of Sockets
  • Stream sockets (a.k.a., TCP)
  • Datagram sockets (a.k.a., UDP)
  • The sockets library that we will use is actually
    very flexible, and supports many types of
    communication

Sockets
5
TCP Sockets
  • TCP Transmission Control Protocol
  • reliable, connection-oriented
  • two-way connection
  • messages sent in order arrive in order
  • like the telephone system

Sockets
6
TCP Sockets
  • A connection must be established between the
    sender and the receiver
  • A conversation takes place
  • The connection must be ended

Sockets
7
TCP Sockets Applications
  • FTP File Transfer Protocol
  • HTTP HyperText Transfer Protocol
  • SMTP Simple Mail Transfer Protocol
  • . . . are all built over TCP

Sockets
8
The top half of TCP/IP
  • IP Internet Protocol
  • is the protocol that ties all computers (devices)
    on the Internet together
  • TCP is a transport layer protocol built over IP

Sockets
9
UDP Sockets
  • UDP User Datagram Protocol
  • connectionless, unreliable
  • communication is not guaranteed to arrive, and
    may not arrive in order
  • like the post office

Sockets
10
UDP Sockets
  • Dont require set up or tear down of a connection
  • Generally used for packet-by-packet transfers of
    information
  • UDP applications include TFTP, BOOTP

Sockets
11
User Datagram Protocol
  • UDP is also a transport layer protocol built over
    IP
  • Generally, UDP applications implement
    acknowledgements to ensure that the packets
    arrive. (TCP does this for you so you dont have
    to!)

Sockets
12
The Layered Network Model
Application (e.g., FTP, HTTP, telnet)
Transport (e.g., TCP, UDP)
Network (e.g., IP)
Data Link (e.g., Ethernet)
Physical (e.g., cables, etc.)
Network Model
13
When a message is sent
  • The application constructs a message

user data
Network Model
14
When a message is sent
  • The message is packaged (encapsulated) with a
    header from the transport layer (e.g., TCP) and
    sent to the network layer

user data
TCP
Network Model
15
When a message is sent
  • The network layer adds a header

user data
TCP
IP
Network Model
16
When a message is sent
  • The data link layer adds a header, and the frame
    is sent out on the network

user data
TCP
IP
Ethernet
Network Model
17
When a message is sent
Application builds message in user memory
Network Model
18
Client/Server Model
Server
Client
  • Starts first
  • Waits for contact from a client
  • Responds to requests
  • Starts second
  • Contacts a server with a request
  • Waits for response from server

Client/Server Model
19
Types of Servers
  • A server can be

Iterative
Concurrent
iterative stateful
concurrent stateful
Stateful
iterative stateless
concurrent stateless
Stateless
Types of Servers
20
Stateful Server
  • Maintains some information between requests
  • Requires smaller messages, since some information
    is kept between contacts
  • May become confused if a connection terminates
    abnormally (if the design is not fault tolerant)
  • Example FTP

Types of Servers
21
Stateless Server
  • Requires larger messages. That is, the message
    must contain all information about the request
    since no state information is kept.
  • Example HTTP

Types of Servers
22
Iterative Server
  • while (1)
  • accept a connection (or request)
  • from a client
  • service the client
  • close the connection (if necessary)

Types of Servers
23
Concurrent Server
  • while (1)
  • accept a connection/request from client
  • start a new thread to handle this client
  • / the thread must close the connection! /

Types of Servers
24
Internet Addressing
  • Suppose you type
  • http//comp.uark.edu/aapon
  • This invokes the HTTP protocol (over TCP/IP), and
    the computer comp.uark.edu is sent a message

Addressing
25
Internet Addressing
Find the home page of user aapon
  • http//comp.uark.edu/aapon/
  • Same as IP address 130.184.252.197

Contact the HTTP server on the computer named
comp.uark.edu
Addressing
26
Internet Addressing
  • A Domain Name Server (DNS) may be called to find
    the IP address of comp.uark.edu
  • Each IP machine is usually configured with the
    name of a DNS server.
  • Some IP names and addresses can also be stored in
    /etc/hostfile

Addressing
27
Internet Addressing
  • http says send the message to port 80
  • An IP address includes both a host address and a
    port number!
  • The HTTP server listens to port 80
  • The HTTP server responds when a client contacts
    it

Addressing
28
Internet Addressing
  • You can write a server that listens to any port
    not already in use!
  • A port number is a 16-bit integer. Ports below
    1024 are reserved for system use.
  • Well-known ports include FTP, Telnet, SMTP, etc.

Addressing
29
Basic Socket Calls
  • struct sockaddr, htons
  • Server calls socket, bind, listen, accept,
    recv, send, close
  • Client calls socket, connect, send, recv, close
  • gethostbyname, getprotobyname

Socket Calls
30
A Socket Descriptor
  • just an int
  • int sd
  • It will point to a socket structure in memory

Socket Calls
31
Create a socket
  • socket()
  • Returns a socket descriptor that you can use in
    later sockets calls (equivalent to fopen() for
    files)
  • sd socket(AF_INET, SOCK_STREAM, 0)

protocol
domain
type
Socket Calls
32
Socket Address Structure
  • struct sockaddr
  • unsigned short sa_family
  • char sa_data14

address family ? AF_INET
14 bytes of protocol address
Socket Calls
33
Socket Address for Internet
  • struct sockaddr_in / for convenience /
  • short int sin_family
  • unsigned short int sin_port / 2 bytes /
  • struct in_addr sin_addr/ 4 bytes /
  • unsigned char sin_zero8

Socket Calls
34
Watch out for Endians!
  • The sin_port and sin_address must be in Network
    Byte Order, which is (possibly) different from
    Host Byte Order
  • Conversion routines include
  • htons - Host to Network Short
  • htonl - Host to Network Long
  • Also ntohs and ntohl

Socket Calls
35
The Server Calls Bind()
  • int sd
  • struct sockaddr_in my_addr
  • sd socket(AF_INET, SOCK_STREAM, 0)
  • my_addr.sin_family AF_INET
  • my_addr.sin_port htons(MYPORT) / use 0 for
    default /
  • my_addr.sin_addr.s_addrINADDR_ANY / is really
    0 /
  • bzero((my_addr.sin_zero), 8)
  • bind(sd, (struct sockaddr ) my_addr,
    sizeof(struct sockaddr))

typecast
size of the address
descriptor
Socket Calls
36
Bind()
  • Finishes filling the socket structure with
    address and port information in the server
  • Specifies the port that the server will listen to
  • Largest port allowed is

65535
Socket Calls
37
The Server Calls listen()
  • define QLEN 6
  • listen(sd, QLEN)

maximum number of requests that can be queued
socket descriptor
Listen is NOT a blocking call!
Socket Calls
38
The Server Calls accept()
  • accept() is a blocking call!
  • sin_size sizeof(struct sockaddr_in)
  • nsd accept(sd, their_addr, sin_size)
  • nsd is a new descriptor -- send/recv on it
  • old sd is still there, and can be used again

Socket Calls
39
A Typical Iterative Server
  • socket()
  • bind()
  • listen()
  • while(1)
  • accept()
  • / do some work with the client /
  • close()

Block here, waiting for a connection!
Socket Calls
40
The Client Calls connect()
  • struct sockaddr_in dest_addr
  • sd socket(AF_INET, SOCK_STREAM, 0)
  • dest_addr.sin_family AF_INET
  • dest_addr.sin_port htons(DEST_PORT)
  • dest_addr.sin_addr.s_addr inet_addr(DEST_IP)
  • bzero((dest_addr.sin_zero), 8)
  • connect(sd, (struct sockaddr )dest_addr,
    sizeof(struct sockaddr))

Socket Calls
41
Sending
  • char msg Amy was here!"
  • int len, bytes_sent
  • len strlen(msg)
  • bytes_sent send(sd, msg, len, 0)

flags
Socket Calls
42
Receiving Stream Sockets
  • numbytes recv(sd, buf, BUFSIZE, 0)
  • while(numbytesgt0)
  • bufnumbytes \0
  • printf(s, buf)
  • numbytes recv(sd, buf, BUFSIZE, 0)

Socket Calls
43
Close the Socket
  • close(sd)
  • Closes the open socket
  • Frees memory and allows the socket descriptor to
    be re-used for a different socket

Socket Calls
44
Utility Functions
  • Gethostbyname()
  • Does a DNS call, if necessary. Converts an IP
    name to an IP address
  • Getprotobyname()
  • Returns a pointer to a protocol table entry, to
    be sure that TCP (or UCP) is known

Socket Calls
45
/ To compile me in Solaris, type gcc -o client
client.c -lsocket -lnsl / / To compile me in
Linux, type gcc -o client client.c / /
client.c - code for example client that uses TCP
/ / From Computer Networks and Internets
by Douglas F. Comer / include
ltsys/types.hgt include ltsys/socket.hgt include
ltnetinet/in.hgt include ltarpa/inet.hgt include
ltnetdb.hgt include ltstdio.hgt include
ltstring.hgt define closesocket
close define PROTOPORT 5193 /
default protocol port number /
Example Client
46
extern int errno char
localhost "localhost" / default host
name / /-----------------------------
----------------------------------------
Program client Purpose allocate a
socket, connect to a server, and print all
output Syntax client host port
host - name of a computer on
which server is executing port -
protocol port number server is using Note
Both arguments are optional. If no host name
is specified, the client uses
"localhost" if no protocol port is
specified, the client uses the default given by
PROTOPORT. ----------------------------------
----------------------------------- /
Example Client
47
main(int argc, char argv) struct hostent
ptrh / pointer to a host table entry
/ struct protoent ptrp / point to a
protocol table entry / struct
sockaddr_in sad / structure to hold server's
address / int sd /
socket descriptor / int
port / protocol port number
/ char host / pointer
to host name / int n
/ number of characters read
/ char buf1000 / buffer for
data from the server / memset((char
)sad,0,sizeof(sad)) / clear sockaddr
structure / sad.sin_family AF_INET
/ set family to Internet / / Check
command-line argument for protocol port and
extract / / port number if on is
specified. Otherwise, use the default / /
port value biven by constant PROTOPORT
/
Example Client
48
if (argc gt 2) port atoi(argv2) else port
PROTOPORT if (port gt 0) sad.sin_port
htons((u_short)port) else fprintf(
stderr,"bad port number s\n", argv2)
exit(1) if (argc gt 1 ) host
argv1 else host localhost ptrh
gethostbyname(host) if( ((char )ptrh)
NULL) fprintf( stderr, "invalid host
s\n", host) exit(1)
Example Client
49
memcpy(sad.sin_addr, ptrh-gth_addr,
ptrh-gth_length) if ( ((int)(ptrp
getprotobyname("tcp"))) 0) fprintf(
stderr, "cannot map \"tcp\" to protocol
number\n") exit(1) sd
socket(PF_INET, SOCK_STREAM, ptrp-gtp_proto)
if (sd lt 0) fprintf( stderr, "socket
creation failed\n") exit(1)
if (connect(sd, (struct sockaddr )sad,
sizeof(sad)) lt 0) fprintf( stderr,
"connect failed\n") exit(1)
Example Client
50
n recv(sd, buf, sizeof(buf), 0) while(n
gt 0) bufn '\0'
printf("CLIENT s", buf) n recv(sd,
buf, sizeof(buf), 0)
closesocket(sd) exit(0)
Example Client
51
/ to compile me on Solaris, type gcc -o
server server.c -lsocket -lnsl / / to compile
me in Linux, type gcc -o server server.c
/ / server.c - code for example server program
that uses TCP / / From Computer Networks and
Internets by Douglas F. Comer / define
closesocket close include ltsys/types.hgt include
ltsys/socket.hgt include ltnetinet/in.hgt include
ltnetdb.hgt include ltstdio.hgt include
ltstring.hgt define PROTOPORT 5193
/ default protocol port number / define QLEN
6 / size of request
queue / int visits 0
/ counts client connections /
Example Server
52
/------------------------------------------------
---------------------------- Program
server Purpose allocate a socket and
then repeatedly execute the folllowing
(1) wait for the next connection
from a client (2) send
a short message to the client
(3) close the connection
(4) go back to step (1) Syntax
server port
port - protocol port number to use Note
The port argument is optional. If no
port is specified, the
server uses the default given by
PROTOPORT. ------------------------------------
---------------------------------------- /
Example Server
53
main (argc, argv) int argc char
argv struct hostent ptrh /
pointer to a host table entry / struct
protoent ptrp / pointer to a protocol
table entry / struct sockaddr_in sad
/ structure to hold server's address /
struct sockaddr_in cad / structure to
hold client's address / int sd, sd2
/ socket descriptors / int
port / protocol port number /
int alen / length of
address / char buf1000 /
buffer for string the server sends /
memset((char )sad,0,sizeof(sad)) / clear
sockaddr structure / sad.sin_family
AF_INET / set family to Internet
/ sad.sin_addr.s_addr INADDR_ANY /
set the local IP address /
Example Server
54
/ Check command-line argument for
protocol port and extract / / port
number if one is specfied. Otherwise, use the
default / / port value given by
constant PROTOPORT /
if (argc gt 1) /
if argument specified /
port atoi (argv1) / convert argument to
binary/ else port
PROTOPORT / use default port number /
if (port gt 0)
/ test for illegal value /
sad.sin_port htons((u_short)port)
else / print
error message and exit /
fprintf (stderr, "bad port number
s/n",argv1) exit (1)

Example Server
55
/ Map TCP transport protocol name to protocol
number / if ( ((int)(ptrp
getprotobyname("tcp"))) 0)
fprintf(stderr, "cannot map \"tcp\" to
protocol number") exit
(1) / Create a socket / sd
socket (PF_INET, SOCK_STREAM, ptrp-gtp_proto)
if (sd lt 0)
fprintf(stderr, "socket creation failed\n")
exit(1)
Example Server
56
/ Bind a local address to the socket / if
(bind(sd, (struct sockaddr )sad, sizeof (sad))
lt 0) fprintf(stderr,"bin
d failed\n") exit(1)
/ Specify a size of request queue / if
(listen(sd, QLEN) lt 0)
fprintf(stderr,"listen failed\n")
exit(1)
Example Server
57
/ Main server loop - accept and handle requests
/ printf("Server up and running.\n")
while (1) alen sizeof(cad)
fprintf( stderr, "SERVER Waiting for contact
...\n") if ( (sd2accept(sd,
(struct sockaddr )cad, alen)) lt 0)
fprintf(stderr, "accept
failed\n") exit
(1) visits
sprintf(buf,"This server has been contacted d
times\n", visits,
visits1?".""s.") printf("SERVER
s", buf) send(sd2,buf,strlen(buf),0)
closesocket (sd2)
Example Server
Write a Comment
User Comments (0)
About PowerShow.com