Part 2 Socket Programming UDP.

Slides:



Advertisements
Similar presentations
Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Advertisements

Computer Net Lab/Praktikum Datenverarbeitung 2 1 Overview Sockets Sockets in C Sockets in Delphi.
Socket Programming Application Programming Interface.
Socket Programming: a Primer Socket to me!. Feb. 23, 2001EE122, UCB2 Why does one need sockets? application network protocol sockets network.
תקשורת באינטרנט Tutorial 8. 2 n Socket programming u What is socket ? u Sockets architecture u Types of Sockets u The Socket system calls u Data Transfer.
1 Pertemuan 10 Non Blocking Matakuliah: H0483 / Network Programming Tahun: 2005 Versi: 1.0.
Tutorial 8 Socket Programming
CSE/EE 461 Getting Started with Networking. Basic Concepts  A PROCESS is an executing program somewhere.  Eg, “./a.out”  A MESSAGE contains information.
1) The server should be concurrent. This implies that it should loop infinitely, listening for clients requests. It should NOT terminate after accepting.
Client Server Model The client machine (or the client process) makes the request for some resource or service, and the server machine (the server process)
2: Application Layer 1 Chapter 2 Application Layer Computer Networking: A Top Down Approach, 5th edition. Jim Kurose, Keith Ross Addison-Wesley, April.
Client Software Design Objectives: Understand principles of C/S design, with focus on clients Review Windows implementations of Socket functions.
Reliable Data Transfer Protocol IMPLEMENTATION TIPS.
Cs423-cotter1 Example Client Program Reference Comer & Stevens, Chapter 7.
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.
ECE 4110 – Internetwork Programming Client-Server Model.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Socket Programming. Introduction Sockets are a protocol independent method of creating a connection between processes. Sockets can be either – Connection.
Sirak Kaewjamnong Computer Network Systems
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.
Socket Programming Lec 2 Rishi Kant. Review of Socket programming Decide which type of socket – stream or datagram. Based on type create socket using.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
CPSC 441 TUTORIAL – FEB 13, 2012 TA: RUITNG ZHOU UDP REVIEW.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
Cli/Serv.: sockets 3/91 Client/Server Distributed Systems v Objectives –describe iterative clients and servers using the UDP protocol ,
CSCE 515: Computer Network Programming UDP Socket Wenyuan Xu Department of Computer Science and Engineering.
Introduction to Socket
CSE/EE 461 Getting Started with Networking. 2 Basic Concepts A PROCESS is an executing program somewhere. –Eg, “./a.out” A MESSAGE contains information.
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
Chapter 2 Applications and Layered Architectures 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,
Programming with UDP – II Covered Subjects: Creating UDP sockets Client Server Sending data Receiving data Connected mode.
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 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
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)
Lecture 3 TCP and UDP Sockets CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
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.
1 UDP Sockets Programming Creating UDP sockets.Creating UDP sockets. –Client –Server Sending data.Sending data. Receiving data.Receiving data. Connected.
Sockets and Beginning Network Programming
Socket programming in C
Socket programming Péter Verhás August 2002
CS 1652 Jack Lange University of Pittsburgh
Socket Programming (Cont.)
Internet Address Routines
Imam Ahmad Trinugroho, ST., MMSI
Transport layer API: Socket Programming
UNIX Sockets Outline Homework #1 posted by end of day
UDP Sockets Programming
Berkeley API Socket Programming
Chapter 2: Application layer
Socket Programming in C
Berkeley API Socket Programming
Chapter 2: Application layer
Chapter 06. UDP Server/Client.
Client-side Networking CSE 333 Summer 2018
Chapter 3 Socket API © Bobby Hoggard, Department of Computer Science, East Carolina University These slides may not be used or duplicated without permission.
Socket Programming(1/2)
Internet Networking recitation #8
Berkeley API Socket Programming
Socket Programming with UDP
Socket programming in C
Chapter 2: Application layer
Presentation transcript:

Part 2 Socket Programming UDP

Socket programming with UDP UDP: no “connection” between client and server no handshaking sender explicitly attaches IP address and port of destination to each packet server must extract IP address, port of sender from received packet UDP: transmitted data may be received out of order, or lost application viewpoint: UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server Application 2-2

Client/Server Socket Interaction: UDP No handshaking. No streams are attached to the sockets. Sender creates packets of bytes with destination IP address and Port number. Receiving host must unravel each packet received to obtain the packet’s information bytes.

Client/server socket interaction: UDP Server (running on hostid) create socket, Client Create datagram with server (hostid, port=x), send datagram via clientSocket create socket, port= x. clientSocket = socket(PF_INET, SOCK_DGRAM,0) serverSocket = socket(PF_INET, SOCK_DGRAM,0) read datagram from serverSocket close clientSocket read datagram from write reply to serverSocket specifying client address, port number Application 2-4

Example: UDP client Client process client UDP socket Input: receives packet (recall that TCP receives a “byte stream”) Output: sends packet (recall that TCP sends a “byte stream”) client UDP socket Application 2-5

Functions and Data Structures

sendto() Send data through a socket: sendto(SOCKET s, char *msg, int msglen, int flags, struct sockaddr *to, int *tolen); PARAMETERS s = socket (inside the socket descriptor: port and IP address...) msg = a pointer to a buffer (could be a string) msglen = the length of the buffer flags = 0 (forget about them for this exercise...) to=structure of address with the IP / port # tolen=length of the structure The WSAStartup function is called to initiate use of WS2_32.dll. Every Winsock application must load the appropriate version of the Winsock DLL. If you fail to load the Winsock library before calling a Winsock function, the function will return a SOCKET_ERROR and the error will be WSANOTINITIALISED . Loading the Winsock library is accomplished by calling the WSAStartup function WSVERS The high order byte specifies the minor version (revision) number; the low-order byte specifies the major version number. Example: sendto(s, sbuffer, strlen(sbuffer),0,(struct sockaddr*) to, &len);

recvfrom() Receive data int recvfrom(SOCKET s, char *msg, int msglen, int flags, struct sockaddr *from, int *fromlen) PARAMETERS s = socket (inside the socket descriptor: port and IP address...) msg = a pointer to a buffer msglen = the length of the buffer flags = 0 from =structure of address with the IP / port # fromlen=length of the structure The WSAStartup function is called to initiate use of WS2_32.dll. Every Winsock application must load the appropriate version of the Winsock DLL. If you fail to load the Winsock library before calling a Winsock function, the function will return a SOCKET_ERROR and the error will be WSANOTINITIALISED . Loading the Winsock library is accomplished by calling the WSAStartup function WSVERS The high order byte specifies the minor version (revision) number; the low-order byte specifies the major version number. Example: recvfrom(s, rbuffer, 1, 0,(struct sockaddr *) &from, &len);

Demo

Test the UDP Client-Server Codes Run the server: ServerUDP 1235 Compile ClientUDP.c, look for the executable. Run ClientUDP.exe from the command prompt to connect to the server: ClientUDP localhost 1235 or ClientUDP 127.0.0.1 1235 Alternatively, use IpConfig to find out what your IP address is: (e.g. 130.123.123.111), then connect to the server using: ClientUDP 130.123.123.111 1235

Source Codes

Client UDP clientUDP.cpp #include <stdio.h> //In LINUX #include <string.h> #include <stdlib.h> #include <winsock2.h> #define WSVERS MAKEWORD(2,0) WSADATA wsadata; #define BUFFERSIZE 80 #define SEGMENTSIZE 78 void get_keyboard(char * send_buffer) { fgets(send_buffer,SEGMENTSIZE,stdin); if (send_buffer[strlen(send_buffer)-1]=='\n') { //if the last one is \n, which means there is at least one ‘\0’ after it send_buffer[strlen(send_buffer)-1]='\r'; send_buffer[strlen(send_buffer)]='\n'; } else { send_buffer[strlen(send_buffer)]='\n'; //write \n on the last byte clientUDP.cpp //In LINUX #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h>

Client UDP clientUDP.cpp int main(int argc, char *argv[]) { //******************************************************************* // Initialization struct sockaddr_in localaddr,remoteaddr; memset(&localaddr, 0, sizeof(localaddr));//clean up memset(&remoteaddr, 0, sizeof(remoteaddr));//clean up //******************************************************************** // WSSTARTUP if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); printf("WSAStartup failed\n"); } int s; char send_buffer[BUFFERSIZE],receive_buffer[BUFFERSIZE]; int n,bytes; if (argc == 1) { printf("USAGE: client IP-address [port]\n"); exit(1); //Port number: get it from argv[2], convert/copy to sin_port if (argc == 3) remoteaddr.sin_port = htons((u_short)atoi(argv[2])); else remoteaddr.sin_port = htons(1234); //Family of protocols remoteaddr.sin_family = AF_INET; clientUDP.cpp The WSAStartup function is called to initiate use of WS2_32.dll. Every Winsock application must load the appropriate version of the Winsock DLL. If you fail to load the Winsock library before calling a Winsock function, the function will return a SOCKET_ERROR and the error will be WSANOTINITIALISED . Loading the Winsock library is accomplished by calling the WSAStartup function WSVERS The high order byte specifies the minor version (revision) number; the low-order byte specifies the major version number.

Client UDP clientUDP.cpp //******************************************************************* //GETHOSTBYNAME struct hostent *h; if ((h=gethostbyname(argv[1])) != NULL) { memcpy(&remoteaddr.sin_addr,h->h_addr,h->h_length); //get remote IP address } else if ((remoteaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE) { printf("An error occured when trying to translate to IP address\n"); exit(1); } //CREATE CLIENT'S SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) { printf("socket failed\n"); printf("\nSOCKET created.\n"); memset(send_buffer, 0, sizeof(send_buffer));//clean up printf("\nwaiting for user input...\n"); clientUDP.cpp

Client UDP clientUDP.cpp get_keyboard(send_buffer); while (strncmp(send_buffer,".",1) != 0) { //******************************************************************* //SEND bytes = sendto(s, send_buffer, strlen(send_buffer),0, (struct sockaddr *)(&remoteaddr),sizeof(remoteaddr) ); printf(“TO SENDER: %s \n",send_buffer); if (bytes < 0) { printf("send failed\n"); exit(1); } memset(send_buffer, 0, sizeof(send_buffer));//clean up closesocket(s); //close(s); //in Linux return 0; clientUDP.cpp

Server UDP serverUDP.cpp #include <errno.h> #include <stdio.h> #include <string.h> #include <winsock2.h> #define WSVERS MAKEWORD(2,0) WSADATA wsadata; #ifndef INET_ADDRSTRLEN #define INET_ADDRSTRLEN 16 #endif int main(int argc, char *argv[]) { //******************************************************************** // INITIALIZATION struct sockaddr_in localaddr,remoteaddr; int s; char send_buffer[80],receive_buffer[80]; char remoteIP[INET_ADDRSTRLEN]; int remotePort=1234; int localPort;//no need for local IP... int n,bytes,addrlen; memset(&localaddr,0,sizeof(localaddr));//clean up the structure memset(&remoteaddr,0,sizeof(remoteaddr));//clean up the structure serverUDP.cpp

Server UDP serverUDP.cpp //******************************************************************** // WSSTARTUP if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); printf("WSAStartup failed\n"); } //SOCKET s = socket(PF_INET, SOCK_DGRAM, 0); if (s <0) { printf("socket failed\n"); localaddr.sin_family = AF_INET; if (argc == 2) localaddr.sin_port = htons((u_short)atoi(argv[1])); else localaddr.sin_port = htons(1235);//default port localaddr.sin_addr.s_addr = INADDR_ANY;//server address should be local //BIND (notice, no listen()...)? if (bind(s,(struct sockaddr *)(&localaddr),sizeof(localaddr)) != 0) { printf("Bind failed!\n"); return 1; serverUDP.cpp

Server UDP serverUDP.cpp //INFINITE LOOP //******************************************************************** while (1) { addrlen = sizeof(struct sockaddr_in); //RECEIVE printf("Waiting... \n"); bytes = recvfrom(s, receive_buffer, 78, 0,(struct sockaddr *)(&remoteaddr),&addrlen); printf("Received %d bytes\n",bytes); //PROCESS REQUEST n=0; while (n<bytes){ n++; if ((bytes < 0) || (bytes == 0)) break; if (receive_buffer[n] == '\n') { /*end on a LF*/ receive_buffer[n] = '\0'; break; } if (receive_buffer[n] == '\r') /*ignore CRs*/ printf("After processing, recvbuffer is %s \n",receive_buffer); closesocket(s); return 0; serverUDP.cpp

EXTRA

fgets function char * fgets ( char * str, int num, FILE * stream ); <cstdio> char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string. Parameters str Pointer to an array of chars where the string read is stored. num Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used. stream Pointer to a FILE object that identifies the stream where characters are read from. To read from the standard input, stdin can be used for this parameter. www.cplusplus.com

memset function void * memset ( void * ptr, int value, size_t num ); <cstring> void * memset ( void * ptr, int value, size_t num ); Fill block of memory Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). Parameters ptr Pointer to the block of memory to fill. value Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value. num Number of bytes to be set to the value. www.cplusplus.com

The End