client server programming using bsd sockets l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Client/Server Programming Using BSD Sockets PowerPoint Presentation
Download Presentation
Client/Server Programming Using BSD Sockets

Loading in 2 Seconds...

play fullscreen
1 / 57

Client/Server Programming Using BSD Sockets - PowerPoint PPT Presentation


  • 196 Views
  • Uploaded on

Client/Server Programming Using BSD Sockets. Short Presentation by Amy Apon. Client/Server Programming Outline. 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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Client/Server Programming Using BSD Sockets' - renate


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
client server programming using bsd sockets

Client/Server ProgrammingUsing BSD Sockets

Short Presentation

by Amy Apon

client server programming outline
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

Client/Server Programming

what is a socket
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

Client/Server Programming

Sockets

two types of sockets
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

Client/Server Programming

Sockets

tcp sockets
TCP Sockets

TCP = Transmission Control Protocol

  • reliable, connection-oriented
  • two-way connection
  • messages sent in order arrive in order
  • like the telephone system

Client/Server Programming

Sockets

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

Client/Server Programming

Sockets

tcp sockets applications
TCP Sockets Applications
  • FTP = File Transfer Protocol
  • HTTP = HyperText Transfer Protocol
  • SMTP = Simple Mail Transfer Protocol

. . . are all built over TCP

Client/Server Programming

Sockets

the top half of tcp ip
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

Client/Server Programming

Sockets

udp sockets
UDP Sockets

UDP = User Datagram Protocol

  • connectionless, unreliable
  • communication is not guaranteed to arrive, and may not arrive in order
  • like the post office

Client/Server Programming

Sockets

udp sockets10
UDP Sockets
  • Don’t require set up or tear down of a connection
  • Generally used for packet-by-packet transfers of information
  • UDP applications include TFTP, BOOTP

Client/Server Programming

Sockets

user datagram protocol
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 don’t have to!)

Client/Server Programming

Sockets

the layered network model
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.)

Client/Server Programming

Network Model

when a message is sent
When a message is sent
  • The application constructs a message

user data

Client/Server Programming

Network Model

when a message is sent14
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

TCP

user data

Client/Server Programming

Network Model

when a message is sent15

An IP packet

When a message is sent
  • The network layer adds a header

IP

TCP

user data

Client/Server Programming

Network Model

when a message is sent16

An Ethernet frame

When a message is sent
  • The data link layer adds a header, and the frame is sent out on the network

Ethernet

IP

TCP

user data

Client/Server Programming

Network Model

when a message is sent17

Message arrives to user memory and the application is notified

Message arrives to user memory and the application is notified

Message arrives to user memory and the application is notified

You only see the communication at THIS LEVEL

Message is copied to kernel and TCP/IP and Ethernet headers are added

Message is copied to kernel and TCP/IP and Ethernet headers are stripped

Message is sent onto network to receiver

When a message is sent

Application builds message in user memory

Client/Server Programming

Network Model

client server model
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 Programming

Client/Server Model

types of servers
Types of Servers

A server can be:

Iterative

Concurrent

iterative stateful

concurrent stateful

Stateful

iterative stateless

concurrent stateless

Stateless

Client/Server Programming

Types of Servers

stateful server
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

Client/Server Programming

Types of Servers

stateless server
Stateless Server
  • Requires larger messages. That is, the message must contain all information about the request since no state information is kept.
  • Example: HTTP

Client/Server Programming

Types of Servers

iterative server
Iterative Server

while (1) {

accept a connection (or request)

from a client

service the client

close the connection (if necessary)

}

Client/Server Programming

Types of Servers

concurrent server
Concurrent Server

while (1) {

accept a connection/request from client

start a new thread to handle this client

/* the thread must close the connection! */

}

Client/Server Programming

Types of Servers

internet addressing
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

Client/Server Programming

Addressing

internet addressing25
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

Client/Server Programming

Addressing

internet addressing26
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

Client/Server Programming

Addressing

internet addressing27
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

Client/Server Programming

Addressing

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

Client/Server Programming

Addressing

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

Client/Server Programming

Socket Calls

a socket descriptor
A Socket Descriptor
  • just an int

int sd;

It will point to a socket structure in memory

Client/Server Programming

Socket Calls

create a socket
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)

domain

type

protocol

Client/Server Programming

Socket Calls

socket address structure
Socket Address Structure

struct sockaddr {

unsigned short sa_family;

char sa_data[14];

};

address family  AF_INET

14 bytes of protocol address

Client/Server Programming

Socket Calls

socket address for internet
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_zero[8];

};

Client/Server Programming

Socket Calls

watch out for endians
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

Client/Server Programming

Socket Calls

the server calls bind
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_addr=INADDR_ANY; /* is really 0 */

bzero(&(my_addr.sin_zero), 8);

bind(sd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr));

descriptor

typecast

size of the address

Client/Server Programming

Socket Calls

slide36
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

Client/Server Programming

Socket Calls

the server calls listen
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!

Client/Server Programming

Socket Calls

the server calls accept
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

Client/Server Programming

Socket Calls

a typical iterative server
A Typical Iterative Server

socket();

bind();

listen();

while(1) {

accept();

/* do some work with the client */

close();

}

Block here, waiting for a connection!

Client/Server Programming

Socket Calls

the client calls connect
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));

Client/Server Programming

Socket Calls

sending
Sending

char *msg = “Amy was here!";

int len, bytes_sent;

len = strlen(msg);

bytes_sent = send(sd, msg, len, 0);

flags

Client/Server Programming

Socket Calls

receiving stream sockets
Receiving Stream Sockets

numbytes = recv(sd, buf, BUFSIZE, 0);

while(numbytes>0) {

buf[numbytes] = ‘\0’;

printf(“%s”, buf);

numbytes = recv(sd, buf, BUFSIZE, 0);

}

Client/Server Programming

Socket Calls

close the socket
Close the Socket

close(sd);

  • Closes the open socket
  • Frees memory and allows the socket descriptor to be re-used for a different socket

Client/Server Programming

Socket Calls

utility functions
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

Client/Server Programming

Socket Calls

slide45

/* 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 <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#include <stdio.h>

#include <string.h>

#define closesocket close

#define PROTOPORT 5193 /* default protocol port number */

Client/Server Programming

Example Client

slide46

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.

*

*---------------------------------------------------------------------

*/

Client/Server Programming

Example Client

slide47

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 buf[1000]; /* 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 */

Client/Server Programming

Example Client

slide48

if (argc > 2) port = atoi(argv[2]);

else port = PROTOPORT;

if (port > 0) sad.sin_port = htons((u_short)port);

else

{ fprintf( stderr,"bad port number %s\n", argv[2]);

exit(1);

}

if (argc > 1 ) host = argv[1];

else host = localhost;

ptrh = gethostbyname(host);

if( ((char *)ptrh) == NULL)

{ fprintf( stderr, "invalid host: %s\n", host);

exit(1);

}

Client/Server Programming

Example Client

slide49

memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_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->p_proto);

if (sd < 0)

{ fprintf( stderr, "socket creation failed\n");

exit(1);

}

if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0)

{ fprintf( stderr, "connect failed\n");

exit(1);

}

Client/Server Programming

Example Client

slide50

n = recv(sd, buf, sizeof(buf), 0);

while(n > 0)

{

buf[n] = '\0';

printf("CLIENT: %s", buf);

n = recv(sd, buf, sizeof(buf), 0);

}

closesocket(sd);

exit(0);

}

Client/Server Programming

Example Client

slide51

/* 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 <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <stdio.h>

#include <string.h>

#define PROTOPORT 5193 /* default protocol port number */

#define QLEN 6 /* size of request queue */

int visits = 0; /* counts client connections */

Client/Server Programming

Example Server

slide52

/*----------------------------------------------------------------------------/*----------------------------------------------------------------------------

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

*

*----------------------------------------------------------------------------

*/

Client/Server Programming

Example Server

slide53

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 buf[1000]; /* 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 */

Client/Server Programming

Example Server

slide54

/* 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 > 1) { /* if argument specified */

port = atoi (argv[1]); /* convert argument to binary*/

} else {

port = PROTOPORT; /* use default port number */

}

if (port > 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",argv[1]);

exit (1);

}

Client/Server Programming

Example Server

slide55

/* 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->p_proto);

if (sd < 0) {

fprintf(stderr, "socket creation failed\n");

exit(1);

}

Client/Server Programming

Example Server

slide56

/* Bind a local address to the socket */

if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) {

fprintf(stderr,"bind failed\n");

exit(1);

}

/* Specify a size of request queue */

if (listen(sd, QLEN) < 0) {

fprintf(stderr,"listen failed\n");

exit(1);

}

Client/Server Programming

Example Server

slide57

/* 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 ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {

fprintf(stderr, "accept failed\n");

exit (1);

}

visits++;

sprintf(buf,"This server has been contacted %d time%s\n",

visits, visits==1?".":"s.");

printf("SERVER: %s", buf);

send(sd2,buf,strlen(buf),0);

closesocket (sd2);

}

}

Client/Server Programming

Example Server