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

Slides:



Advertisements
Similar presentations
Introduction 1-1 Chapter 3 Transport Layer Intro and Multiplexing Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley.
Advertisements

Socket Programming Application Programming Interface.
Elementary TCP Sockets Computer Networks Computer Networks Term B10 UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
2: Application Layer 1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
Quick Overview. 2 ISO/OSI Reference Model Application Application Presentation Presentation Session Session Transport Transport Network Network Data Link.
1 Socket Interfaces Professor Jinhua Guo CIS527 Fall 2003.
Introduction to Transport Layer. Transport Layer: Motivation A B R1 R2 r Recall that NL is responsible for forwarding a packet from one HOST to another.
Tutorial 8 Socket Programming
UDP: User Datagram Protocol. UDP: User Datagram Protocol [RFC 768] r “bare bones”, “best effort” transport protocol r connectionless: m no handshaking.
CS 311 – Lecture 18 Outline IPC via Sockets – Server side socket() bind() accept() listen() – Client side connect() Lecture 181CS Operating Systems.
Socket Addresses. Domains Internet domains –familiar with these Unix domains –for processes communicating on the same hosts –not sure of widespread use.
1 School of Computing Science Simon Fraser University CMPT 771/471: Internet Architecture and Protocols Socket Programming Instructor: Dr. Mohamed Hefeeda.
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
1 Computer Networks Transport Layer Protocols. 2 Application-layer Protocols Application-layer protocols –one “piece” of an app –define messages exchanged.
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
Process-to-Process Delivery:
Tutorial on Socket Programming Data types and structures for writing client- server programs.
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
Socket programming in C. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
CS1652 September 13th, 2012 The slides are adapted from the publisher’s material All material copyright J.F Kurose and K.W. Ross, All Rights.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Jozef Goetz, Application Layer PART VI Jozef Goetz, Position of application layer The application layer enables the user, whether human.
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
The Application Layer Application Services (Telnet, FTP, , WWW) Reliable Stream Transport (TCP) Connectionless Packet Delivery Service (IP) Unreliable.
Vassil Roussev 2 A socket is the basic remote communication abstraction provided by the OS to processes. controlled by operating system.
Transport Layer and UDP Tahir Azim Ref:
 Wind River Systems, Inc Chapter - 13 Network Programming.
2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley March 2012.
Application Layer 2-1 Chapter 2 Application Layer Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley March 2012.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Application Layer 2-1 Chapter 2 Application Layer Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley March 2012.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
TELE202 Lecture 15 Socket programming 1 Lecturer Dr Z. Huang Overview ¥Last Lecture »TCP/UDP (2) »Source: chapter 17 ¥This Lecture »Socket programming.
University of Calgary – CPSC 441.  A socket is an interface between the application and the network (the lower levels of the protocol stack)  The application.
Introduction to Socket
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 3.1 Internet Applications Ch. 28,… (Client-Server Concept, Use of Protocol Ports, Socket API)
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
Socket Programming Introduction. Socket Definition A network socket is one endpoint in a two-way communication flow between two programs running over.
C Programming in Linux Sockets. All Internet Applications use Sockets to Communicate Servers use passive sockets to listen Clients use active sockets.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
CPSC Application Layer 1 Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: Opens TCP connection to port 80 (default.
Socket programming in C. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
Socket programming in C. Socket programming with TCP Client must contact server server process must first be running server must have created socket (door)
2: Transport Layer 11 Transport Layer 1. 2: Transport Layer 12 Part 2: Transport Layer Chapter goals: r understand principles behind transport layer services:
Socket Programming in C CS587x Lecture 3 Department of Computer Science Iowa State University.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
Introduction to Networks
Socket programming in C
Sockets and Beginning Network Programming
CS 1652 Jack Lange University of Pittsburgh
Introduction to Networks
Transport layer API: Socket Programming
Process-to-Process Delivery:
Socket Programming.
Chapter 2 Application Layer
Socket Programming(1/2)
Internet Networking recitation #8
Socket programming in C
Presentation transcript:

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

Workshop Outline 1. Client-Server Mechanisms 2. How the Applications work 3. Introduction to sockets 4. Socket types 5. Programming with sockets 6. Concurrent Processing 7. Programming project

Workshop References 1. “Computer Networking: A Top Down Approach Featuring the Internet” Kurose and Ross, Addison Wesley “Internetworking with TCP/IP Vol 3: Client- Server Programming and Applications” Comer and Stevens, Prentice Hall “Hands on Networking” Doug Comer 2 nd edition Pearson Prentice Hall “An Introduction to Network Programming with Java” Jan Graba Pearson Addison Wesley 2003

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 other When the person starts the first program on machine M1, this program sends a message to the program on machine M2 Since 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

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.

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 client The other program is called the client and the client is supposed to initiate the communication by sending a message to the server

Client-server paradigm Typical network app has two pieces: client and server application transport network data link physical application transport network data link physical Client: initiates contact with server (“speaks first”) typically requests service from server, for Web, client is implemented in browser; for , in mail reader Server: provides requested service to client e.g., Web server sends requested Web page, mail server delivers e- mail request reply

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

application transport network M P2 application transport network Multiplexing/demultiplexing segment - unit of data exchanged between transport layer entities aka TPDU: transport protocol data unit receiver H t H n Demultiplexing: delivering received segments to correct app layer processes segment M application transport network P1 MMM P3 P4 segment header application-layer data

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 application data (message) other header fields TCP/UDP segment format Multiplexing:

Multiplexing/demultiplexing: examples host A server B source port: x dest. port: 23 source port:23 dest. port: x port use: simple telnet app Web client host A Web server B Web client host C Source IP: C Dest IP: B source port: x dest. port: 80 Source IP: C Dest IP: B source port: y dest. port: 80 port use: Web server Source IP: A Dest IP: B source port: x dest. port: 80

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: 80 FTP: 21 SMTP: 25 POP3: 110 More ports in RFC1700 (

Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly 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/owned, 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

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 with buffers, variables socket controlled by application developer controlled by operating system host or server process TCP with buffers, variables socket controlled by application developer controlled by operating system host or server internet

Socket programming with TCP Client must contact server server process must first be running server must have created socket (door) that welcomes client’s contact Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP When 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

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

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 socket connect() to establish active connection to a server send() to transfer data recv() to receive data close() to terminate the connection

Sockaddr_in struct sockaddr_in { u_char sin_len; //total length u_short sin_family; //type of address u_short sin_port; //protocol port no. struct in_addr sin_addr; //ip address char sin_zero[8]; //unused }

Socket API Client side: socket  connect  send  recv  close Server side: socket  bind  listen  accept  recv  send  close Programs must #include and

Getting Started with Sockets #include int main(void) { int s; s = socket(PF_INET, SOCK_STREAM, 0); printf(“I just got a socket created\n”); return 1; }

Getting Started With Sockets The socket() call takes 3 arguments socket(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

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

Client Side Get remote host information by using the following statements. Do not forget to #include and 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 (“ == 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

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.

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

Client Requests a Web Page #include #define BUFLEN 1024 char 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

Sample Source Code struct sockaddr_in sa; //holds IP address and protocol port req[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 struct if ((ph = gethostbyname (" == NULL) { printf("error in gethostbyname\n"); exit(1); } //now ph has the IP address of the server, copy it to sa memcpy((char *) &sa.sin_addr,ph->h_addr, ph->h_length);

Sample Source Code //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);} 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");

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

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

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

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

TCP Server Initialization #include #definePROTOPORT5193 // port number #defineQLEN6// size of request queue intvisits = 0;// counts client connection

TCP Server Initialization main(argc, argv) intargc; char*argv[]; { structhostent *ptrh; /* pointer to a host table entry*/ structprotoent *ptrp; /* pointer to a protocol table entry*/ structsockaddr_in sad; /* structure to hold server's address*/ structsockaddr_in cad; /* structure to hold client's address*/ intsd, sd2; /* socket descriptors*/ intport; /* protocol port number*/ intalen; /* length of address*/ charbuf[1000]; /* buffer for string the server sends*/

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

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

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

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

Lab 1 First compile and run the server Next 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