39
Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science State University of New York at Fredonia

Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client-Server Network ProgrammingSession 1: Introduction to Sockets and socket types

A workshop by

Dr. Junaid Ahmed ZubairiDepartment of Computer ScienceState University of New York at Fredonia

Page 2: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Workshop Outline

1. Client-Server Mechanisms2. How the Applications work3. Introduction to sockets4.Socket types5. Programming with sockets6. Concurrent Processing7. Programming project

Page 3: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Workshop References

1. “Computer Networking: A Top Down Approach Featuring the Internet” Kurose and Ross, Addison Wesley 2001

2. “Internetworking with TCP/IP Vol 3: Client-Server Programming and Applications” Comer and Stevens, Prentice Hall 2001

3. “Hands on Networking” Doug Comer 2nd edition Pearson Prentice Hall 2005

4. “An Introduction to Network Programming with Java” Jan Graba Pearson Addison Wesley 2003

Page 4: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client-Server Mechanisms

Let us assume that a person is trying to start two programs on separate networked machines (M1 and M2) and these programs must communicate with each otherWhen the person starts the first program on machine M1, this program sends a message to the program on machine M2Since the computer works much faster than human beings, the program on M1 waits a few milliseconds for response from M2 and then gives up displaying an error message

Page 5: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client-Server Mechanisms

Meanwhile, our friend reaches M2 and types the second program name to start it on M2 The second program waits for a message from M1 for a few milliseconds and then concludes that the first program is not active yet. It displays an error message and exits.Our friend would keep starting the programs but they will never be able to communicate.

Page 6: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client-Server Mechanisms

The solution is to let one program open up communications and wait indefinitely for a message from the other program The first program to start running is called the server. The server must listen for any message from the clientThe other program is called the client and the client is supposed to initiate the communication by sending a message to the server

Page 7: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client-server paradigmTypical network app has two

pieces: client and serverapplicatio

ntransportnetworkdata linkphysical

application

transportnetworkdata linkphysical

Client:initiates contact with server (“speaks first”)typically requests service from server, for Web, client is implemented in browser; for e-mail, in mail reader

Server:provides requested service to cliente.g., Web server sends requested Web page, mail server delivers e-mail

request

reply

Page 8: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Introduction to Sockets

A machine on the network may be running various network servers (Web, Email, FTP, DNS etc.)Many different clients may contact this machine, all requesting various servicesThe machine services the clients correctly based on the port numbers

Page 9: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

applicationtransportnetwork

MP2

applicationtransportnetwork

Multiplexing/demultiplexing

segment - unit of data exchanged between transport layer entities

aka TPDU: transport protocol data unit

receiver

HtHn

Demultiplexing: delivering received segments to correct app layer processes

segment

segment Mapplicationtransportnetwork

P1M

M MP3 P4

segmentheader

application-layerdata

Page 10: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Multiplexing/demultiplexing

multiplexing/demultiplexing:based on sender, receiver port numbers, IP addresses

source, dest port #s in each segment

well-known port numbers for specific applications

gathering data from multiple app processes, enveloping data with header (later used for demultiplexing)

source port # dest port #

32 bits

applicationdata

(message)

other header fields

TCP/UDP segment format

Multiplexing:

Page 11: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Multiplexing/demultiplexing: examples

host A server Bsource port: xdest. port: 23

source port:23dest. port: x

port use: simple telnet app

Web clienthost A

Webserver B

Web clienthost C

Source IP: CDest IP: B

source port: x

dest. port: 80

Source IP: CDest IP: B

source port: y

dest. port: 80

port use: Web server

Source IP: ADest IP: B

source port: x

dest. port: 80

Page 12: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Well-Known Ports

The application servers listen on well-known ports or “reserved” ports so that every user can connect to them.Some well known ports are as under:HTTP: 80FTP: 21SMTP: 25POP3: 110More ports in RFC1700 (www.ietf.org)

Page 13: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket programming

Socket APIintroduced in BSD4.1 UNIX, 1981explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: unreliable datagram reliable, byte stream-

oriented

a host-local, application-created/own

ed, OS-controlled interface (a “door”) into which

application process can both send and

receive messages to/from another (remote

or local) application

process

socket

Goal: learn how to build client/server application that communicate using sockets

Page 14: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket-programming Socket: a door between application process

and end-end-transport protocol (UDP or TCP)TCP service: reliable transfer of bytes from one

process to another

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperating

system

host orserver

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperatingsystem

host orserver

internet

Page 15: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket programming with TCP

Client must contact serverserver process must first be runningserver must have created socket (door) that welcomes client’s contact

Client contacts server by:creating client-local TCP socketspecifying IP address, port number of server process

When client creates socket: client TCP establishes connection to server TCPWhen contacted by client, server TCP creates new socket for server process to communicate with client

allows server to talk with multiple clients

TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server

application viewpoint

Page 16: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket API

Each socket is identified by its socket descriptorThe OS allocates a new data structure to hold necessary information on creation of a socketA passive socket listens for incoming messages. An active socket is used by a client to initiate connection

Page 17: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket API

For TCP/IP communications, the programs should use predefined structure “sockaddr_in”Major system calls in Socket API are as follows:socket() to create a socketconnect() to establish active connection to a serversend() to transfer datarecv() to receive dataclose() to terminate the connection

Page 18: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Sockaddr_in

struct sockaddr_in {u_char sin_len; //total lengthu_short sin_family; //type of addressu_short sin_port; //protocol port no.struct in_addr sin_addr; //ip addresschar sin_zero[8]; //unused}

Page 19: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Socket API

Client side:socketconnect sendrecvcloseServer side:socketbindlistenacceptrecv sendclosePrograms must #include <sys/types.h> and <sys/socket.h>

Page 20: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Getting Started with Sockets

#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>int main(void) {int s;

s = socket(PF_INET, SOCK_STREAM, 0);printf(“I just got a socket created\n”);return 1;}

Page 21: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Getting Started With Sockets

The socket() call takes 3 argumentssocket(domain,type,protocol) The first argument is the domain.

PF_INET for network sockets PF_UNIX for system sockets

The second argument is the socket type SOCK_DGRAM is for UDP socket SOCK_STREAM is for TCP socket

The third argument is left 0 so that the system can select the correct protocol

System returns a descriptor that can be used to refer to the socket later

Page 22: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Getting Started With Sockets

Once a socket is created, we should be able to connect to a remote machineIf we are on the client side, we need to get the server’s IP address and then try to connect to the server

Page 23: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client Side

Get remote host information by using the following statements. Do not forget to #include <netinet/in.h> and <netdb.h>

struct hostent * ph; //remote host name and info struct sockaddr_in sa; //holds IP address and protocol port memset(&sa, 0, sizeof(sa)); //zero out the sa struct if ((ph = gethostbyname (“www.cs.fredonia.edu”)) == NULL) { printf(“error in gethostbyname\n”); exit(1); }

We tried to get the IP address by using DNS service. If it failed, the program will exit with a nonzero error code. hostent structure is defined in netdb.h

Page 24: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client connects to a web server

//now ph has the IP address of the server, copy it to sa memcpy((char *) &sa.sin_addr,ph->h_addr, ph->h_length); //Fill out the sin_port information by converting the port number to

network byte order sa.sin_port = htons((u_short) 80); sa.sin_family = ph->h_addrtype; if (connect(s, &sa, sizeof(sa) < 0)) { perror(“connect error\n”);exit(1);}

Network byte order is a neutral order for sending numerical quantities. It is used because PC’s store the numbers in opposite way to mainframes and UNIX workstations.

Page 25: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client requests a web page

Now client requests a web page from the server. Let us check out the sample source code and try to understand as to what is going on

Page 26: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Client Requests a Web Page

#include <stdlib.h>#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>

#define BUFLEN 1024char req[40] = "GET /~zubairi/index.html HTTP/1.0\n\n";char buf[BUFLEN];char *bptr;int n;int buflen;int count=0;

main(){int s;struct hostent * ph; //remote host name and info

Page 27: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Sample Source Code

struct sockaddr_in sa; //holds IP address and protocol portreq[39] = '\0';printf("%s",req);s = socket(PF_INET, SOCK_STREAM, 0);printf("Socket was created\n");memset(&sa, 0, sizeof(sa)); //zero out the sa structif ((ph = gethostbyname ("www.cs.fredonia.edu")) == NULL){ printf("error in gethostbyname\n"); exit(1); }//now ph has the IP address of the server, copy it to samemcpy((char *) &sa.sin_addr,ph->h_addr, ph->h_length);

Page 28: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Sample Source Code

//Fill out the sin_port information by converting the//port number to network byte ordersa.sin_port = htons((u_short) 80);sa.sin_family = ph->h_addrtype;if (connect(s, &sa, sizeof(sa)) < 0){ perror("connect error\n");exit(1);}else printf("connected to web server\n");

bptr = buf;buflen = BUFLEN;if (send (s, req, strlen(req), 0)<=0) perror("send error\n");else printf("Sent to the server\n");

Page 29: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Sample Source Code

printf("Now starting to receive\n");

While ( (n = recv(s,bptr,buflen,0) ) > 0){printf("Still receiving\n");count++;}if (!count) printf("Error in receive\n");else printf("received all \n");printf("%s\n",bptr);}

Page 30: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Web client code

C strings are null terminated (\0)Request to get the web page is sent to the web server at port 80Source code receives and displays all pieces receivedYou can also receive and display piece by piece as shown

Page 31: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Web client code

while ( (n = recv(s,bptr,buflen,0) ) > 0){printf("%s",bptr); //print the received databptr = bptr+n; //advance the pointer to buffer beyond received bytesbuflen = buflen –n; //reduce the available buffer length accordingly}

Page 32: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

TCP Server

Following is an example server program from Dr. Comer’s ftp site. It waits for connection from the client, sends a short message to it and then closes connection

Page 33: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

TCP Server Initialization

#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <stdio.h>#include <string.h>#define PROTOPORT 5193 // port number #define QLEN 6 // size of request queueint visits = 0; // counts client connection

Page 34: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

TCP Server Initialization

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

Page 35: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Setting Port No. for TCP Server

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 *//* Check command-line argument for protocol port and extract it

*/if (argc > 1) { /* if argument specified */

port = atoi(argv[1]); /* convert argument to binary */} else port = PROTOPORT; /* else 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);

}

Page 36: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Map Protocol and Create a Socket

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

}

Page 37: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Bind to Socket and Set Queue

/* Bind a local address to the socket */if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {

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

}/* Specify size of request queue */if (listen(sd, QLEN) < 0) {

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

}

Page 38: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Accept Requests and Fulfill

while (1) {alen = sizeof(cad);

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

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

}}

Page 39: Client-Server Network Programming Session 1: Introduction to Sockets and socket types A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science

Lab 1

First compile and run the serverNext modify the client code to set the IP address of the server to the correct value and port number to the correct port.Now the client can be started Each time the client runs, the server keeps incrementing the count of clients served