Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

57
Client/Server Client/Server Programming Programming Using BSD Sockets Using BSD Sockets Short Presentation by Amy Apon

Transcript of Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Page 1: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Client/Server ProgrammingProgrammingUsing BSD SocketsUsing BSD Sockets

Short Presentationby Amy Apon

Page 2: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Client/Server ProgrammingClient/Server ProgrammingOutlineOutline

• What is a socket and what are the two types?What is a socket and what are the two types?

• The layered network modelThe layered network model

• Client/server model and types of serversClient/server model and types of servers

• Internet addressingInternet addressing

• Basic socket calls Basic socket calls

• Sample client and serverSample client and server

Page 3: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

What is a socket?What is a socket?

A way to communicate to other A way to communicate to other programs using a programs using a descriptordescriptor that is that is like a file descriptor. You mustlike a file descriptor. You must

• open itopen it

• read/write read/write oror send/recv send/recv

• close itclose it

Sockets

Page 4: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Two Types of SocketsTwo Types of Sockets

• Stream sockets (a.k.a., TCP)Stream sockets (a.k.a., TCP)

• Datagram sockets (a.k.a., UDP)Datagram sockets (a.k.a., UDP)

The sockets library that we will use is The sockets library that we will use is actually very flexible, and supports actually very flexible, and supports many types of communicationmany types of communication

Sockets

Page 5: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

TCP SocketsTCP Sockets

TCP = Transmission Control ProtocolTCP = Transmission Control Protocol

• reliable, connection-orientedreliable, connection-oriented

• two-way connectiontwo-way connection

• messages sent in order arrive in ordermessages sent in order arrive in order

like the telephone systemlike the telephone system

Sockets

Page 6: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

TCP SocketsTCP Sockets

• A connection must be established A connection must be established between the sender and the between the sender and the receiverreceiver

• A conversation takes placeA conversation takes place

• The connection must be endedThe connection must be ended

Sockets

Page 7: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

TCP Sockets ApplicationsTCP Sockets Applications

• FTP = File Transfer ProtocolFTP = File Transfer Protocol

• HTTP = HyperText Transfer ProtocolHTTP = HyperText Transfer Protocol

• SMTP = Simple Mail Transfer SMTP = Simple Mail Transfer ProtocolProtocol

. . . are all built over TCP. . . are all built over TCP

Sockets

Page 8: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The top half of TCP/IPThe top half of TCP/IP

IP = Internet ProtocolIP = Internet Protocol

• is the protocol that ties all is the protocol that ties all computers (devices) on the Internet computers (devices) on the Internet togethertogether

• TCP is a TCP is a transport layertransport layer protocol protocol built over IPbuilt over IP

Sockets

Page 9: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

UDP SocketsUDP Sockets

UDP = User Datagram ProtocolUDP = User Datagram Protocol

• connectionless, unreliable connectionless, unreliable

• communication is not guaranteed to communication is not guaranteed to arrive, and may not arrive in orderarrive, and may not arrive in order

like the post officelike the post office

Sockets

Page 10: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

UDP SocketsUDP Sockets

• Don’t require set up or tear down of Don’t require set up or tear down of a connectiona connection

• Generally used for packet-by-packet Generally used for packet-by-packet transfers of informationtransfers of information

• UDP applications include TFTP, UDP applications include TFTP, BOOTPBOOTP

Sockets

Page 11: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

User Datagram ProtocolUser Datagram Protocol

• UDP is also a transport layer UDP is also a transport layer protocol built over IPprotocol built over IP

• Generally, UDP applications Generally, UDP applications implement implement acknowledgementsacknowledgements to to ensure that the packets arrive. ensure that the packets arrive. (TCP does this for you so you don’t (TCP does this for you so you don’t have to!)have to!)

Sockets

Page 12: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The Layered Network The Layered Network ModelModel

Physical (e.g., cables, etc.)

Data Link (e.g., Ethernet)

Network (e.g., IP)

Transport (e.g., TCP, UDP)

Application (e.g., FTP, HTTP, telnet)

Network Model

Page 13: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

When a message is sentWhen a message is sent

• The application constructs a The application constructs a messagemessage

user data

Network Model

Page 14: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

When a message is sentWhen a message is sent

• The message is packaged The message is packaged (encapsulated) with a header from (encapsulated) with a header from the transport layer (e.g., TCP) and the transport layer (e.g., TCP) and sent to the network layersent to the network layer

user data

TCP

Network Model

Page 15: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

When a message is sentWhen a message is sent

• The network layer adds a headerThe network layer adds a header

user data

TCPIP

An IP packet

Network Model

Page 16: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

When a message is sentWhen a message is sent

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

user data

TCPIPEthernet

An Ethernet frame

Network Model

Page 17: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

When a message is sentWhen a message is sent

Application builds message in user memory

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

Message is sent onto network to receiver

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

Message arrives to user memory and the application is notified

You only see the communication at

THIS LEVEL

Message arrives to user memory and the application is notified

Message arrives to user memory and the application is notified

Network Model

Page 18: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Client/Server ModelClient/Server Model

•Starts first

•Waits for contact from a client

•Responds to requests

•Starts second

•Contacts a server with a request

•Waits for response from server

Server Client

Client/Server Model

Page 19: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Types of ServersTypes of Servers

A server can be:A server can be:

Types of Servers

Stateful

Stateless

Iterative

Concurrent

iterative stateful

concurrent stateful

iterative stateless

concurrent

stateless

Page 20: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Stateful ServerStateful Server

• Maintains some information between Maintains some information between requestsrequests

• Requires smaller messages, since some Requires smaller messages, since some information is kept between contactsinformation is kept between contacts

• May become confused if a connection May become confused if a connection terminates abnormally (if the design is not terminates abnormally (if the design is not fault tolerant)fault tolerant)

• Example: FTPExample: FTP

Types of Servers

Page 21: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Stateless ServerStateless Server

• Requires larger messages. That is, Requires larger messages. That is, the message must contain all the message must contain all information about the request since information about the request since no state information is kept.no state information is kept.

• Example: HTTPExample: HTTP

Types of Servers

Page 22: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Iterative ServerIterative Server

while (1) {while (1) {

accept a connection (or request)accept a connection (or request) from a clientfrom a client

service the clientservice the client

close the connection (if necessary)close the connection (if necessary)

}}Types of Servers

Page 23: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Concurrent ServerConcurrent Server

while (1) {while (1) {

accept a connection/request from clientaccept a connection/request from client

start a new thread to handle this clientstart a new thread to handle this client

/* the thread must close the connection! *//* the thread must close the connection! */

}}

Types of Servers

Page 24: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Internet AddressingInternet Addressing

• Suppose you type:Suppose you type:

http://comp.uark.edu/~aaponhttp://comp.uark.edu/~aapon

• This invokes the HTTP protocol (over This invokes the HTTP protocol (over TCP/IP), and the computer TCP/IP), and the computer “comp.uark.edu” is sent a message“comp.uark.edu” is sent a message

Addressing

Page 25: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Internet AddressingInternet Addressing

http://comp.uark.edu/~aapon/http://comp.uark.edu/~aapon/

• Same as IP address 130.184.252.197Same as IP address 130.184.252.197

Find the home page of user aaponFind the home page of user aapon

Contact the HTTP server on the Contact the HTTP server on the computer named comp.uark.educomputer named comp.uark.edu

Addressing

Page 26: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Internet AddressingInternet Addressing

• A Domain Name Server (DNS) may be A Domain Name Server (DNS) may be called to find the IP address of called to find the IP address of comp.uark.educomp.uark.edu

• Each IP machine is usually configured Each IP machine is usually configured with the name of a DNS server.with the name of a DNS server.

• Some IP names and addresses can Some IP names and addresses can also be stored in /etc/hostfilealso be stored in /etc/hostfile

Addressing

Page 27: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Internet AddressingInternet Addressing

““http” says: send the message to port http” says: send the message to port 8080

• An IP address includes both a host An IP address includes both a host address and a port number!address and a port number!

• The HTTP server listens to port 80The HTTP server listens to port 80

• The HTTP server responds when a The HTTP server responds when a client contacts itclient contacts it

Addressing

Page 28: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Internet AddressingInternet Addressing

You can write a server that listens You can write a server that listens to any port not already in use!to any port not already in use!

• A port number is a 16-bit integer. A port number is a 16-bit integer. Ports below 1024 are reserved for Ports below 1024 are reserved for system use.system use.

• Well-known ports include FTP, Telnet, Well-known ports include FTP, Telnet, SMTP, etc.SMTP, etc.

Addressing

Page 29: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Basic Socket CallsBasic Socket Calls

• struct sockaddr, htonsstruct sockaddr, htons

• Server calls: socket, bind, listen, Server calls: socket, bind, listen, accept, recv, send, closeaccept, recv, send, close

• Client calls: socket, connect, send, Client calls: socket, connect, send, recv, closerecv, close

• gethostbyname, getprotobynamegethostbyname, getprotobyname

Socket Calls

Page 30: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

A Socket DescriptorA Socket Descriptor

• just an intjust an int

int sd;int sd;

It will point to a socket structure in It will point to a socket structure in memory memory

Socket Calls

Page 31: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Create a socketCreate a socket

• socket()socket()– Returns a socket descriptor that you Returns a socket descriptor that you

can use in later sockets calls can use in later sockets calls (equivalent to fopen() for files)(equivalent to fopen() for files)

sd = socket(AF_INET, SOCK_STREAM, sd = socket(AF_INET, SOCK_STREAM, 0)0)

protocoldomain type

Socket Calls

Page 32: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Socket Address StructureSocket Address Structure

struct sockaddr {struct sockaddr {

unsigned short unsigned short sa_family; sa_family;

char sa_data[14]; char sa_data[14];

};};

address family AF_INET

14 bytes of protocol address

Socket Calls

Page 33: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Socket Address for Socket Address for InternetInternet

struct sockaddr_in { /* for convenience */struct sockaddr_in { /* for convenience */

short int sin_family; short int sin_family;

unsigned short int sin_port; /* 2 bytes unsigned short int sin_port; /* 2 bytes */*/

struct in_addr sin_addr;/* 4 bytes */struct in_addr sin_addr;/* 4 bytes */

unsigned char sin_zero[8]; unsigned char sin_zero[8];

};};

Socket Calls

Page 34: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Watch out for Endians!Watch out for Endians!

• The sin_port and sin_address must be The sin_port and sin_address must be in Network Byte Order, which is in Network Byte Order, which is (possibly) different from Host Byte (possibly) different from Host Byte OrderOrder

• Conversion routines include:Conversion routines include:– htons - “Host to Network Short”htons - “Host to Network Short”– htonl - “Host to Network Long”htonl - “Host to Network Long”Also ntohs and ntohlAlso ntohs and ntohl

Socket Calls

Page 35: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The Server Calls Bind()The Server Calls Bind()

int sd;int sd;struct sockaddr_in my_addr;struct sockaddr_in my_addr;

sd = socket(AF_INET, SOCK_STREAM, 0);sd = socket(AF_INET, SOCK_STREAM, 0);my_addr.sin_family = AF_INET;my_addr.sin_family = AF_INET;my_addr.sin_port = htons(MYPORT); /* use 0 for default my_addr.sin_port = htons(MYPORT); /* use 0 for default */*/my_addr.sin_addr.s_addr=INADDR_ANY; /* is really 0 */my_addr.sin_addr.s_addr=INADDR_ANY; /* is really 0 */bzero(&(my_addr.sin_zero), 8); bzero(&(my_addr.sin_zero), 8);

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

typecast size of the addressdescriptor

Socket Calls

Page 36: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Bind()Bind()

• Finishes filling the socket structure Finishes filling the socket structure with address and port information in with address and port information in the serverthe server

• Specifies the port that the server Specifies the port that the server will listen towill listen to

• Largest port allowed isLargest port allowed is6553655355

Socket Calls

Page 37: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The Server Calls listen()The Server Calls listen()

#define QLEN 6#define QLEN 6

listen(sd, QLEN);listen(sd, QLEN);

socket descriptor

maximum number of requests that can be queued

Listen is NOT a blocking call!

Socket Calls

Page 38: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The Server Calls accept()The Server Calls accept()

accept() is a blocking call!accept() is a blocking call!

sin_size = sizeof(struct sockaddr_in);sin_size = sizeof(struct sockaddr_in);

nsd = accept(sd, &their_addr, &sin_size);nsd = accept(sd, &their_addr, &sin_size);

nsd is a new descriptor -- send/recv on itnsd is a new descriptor -- send/recv on it

old sd is still there, and can be used againold sd is still there, and can be used again

Socket Calls

Page 39: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

A Typical Iterative ServerA Typical Iterative Server

socket();socket();

bind();bind();

listen();listen();

while(1) {while(1) {

accept();accept();

/* do some work with the client *//* do some work with the client */

close();close();

}}

Block here, waiting for a connection!

Socket Calls

Page 40: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

The Client Calls connect()The Client Calls connect()struct sockaddr_in dest_addr;struct sockaddr_in dest_addr;

sd = socket(AF_INET, SOCK_STREAM, 0);sd = socket(AF_INET, SOCK_STREAM, 0);

dest_addr.sin_family = AF_INET; dest_addr.sin_family = AF_INET;

dest_addr.sin_port = htons(DEST_PORT);dest_addr.sin_port = htons(DEST_PORT);

dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);

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

connect(sd, (struct sockaddr *)&dest_addr, connect(sd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr));sizeof(struct sockaddr));

Socket Calls

Page 41: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

SendingSending

char *msg = “Amy was here!";char *msg = “Amy was here!";

int len, bytes_sent;int len, bytes_sent;

len = strlen(msg);len = strlen(msg);

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

flags

Socket Calls

Page 42: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Receiving Stream SocketsReceiving Stream Sockets

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

while(numbytes>0) {while(numbytes>0) {

buf[numbytes] = ‘\0’;buf[numbytes] = ‘\0’;

printf(“%s”, buf);printf(“%s”, buf);

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

}}

Socket Calls

Page 43: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Close the SocketClose the Socket

close(sd);close(sd);

• Closes the open socketCloses the open socket

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

Socket Calls

Page 44: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

Utility FunctionsUtility Functions

• Gethostbyname()Gethostbyname()– Does a DNS call, if necessary. Does a DNS call, if necessary.

Converts an IP name to an IP addressConverts an IP name to an IP address

• Getprotobyname()Getprotobyname()– Returns a pointer to a protocol table Returns a pointer to a protocol table

entry, to be sure that TCP (or UCP) is entry, to be sure that TCP (or UCP) is knownknown

Socket Calls

Page 45: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

Example Client

Page 46: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

Page 47: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

Example Client

Page 48: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Client

Page 49: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Client

Page 50: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Client

Page 51: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

Page 52: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

* 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

Page 53: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

Server

Page 54: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Server

Page 55: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Server

Page 56: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

Example Server

Page 57: Client/Server Programming Using BSD Sockets Short Presentation by Amy Apon.

Client/Server Programming

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

}

}

Example Server