EECS 123: Introduction to Real-Time Distributed Programming

Similar documents
WinSock. What Is Sockets What Is Windows Sockets What Are Its Benefits Architecture of Windows Sockets Network Application Mechanics

A. Basic Function Calls for Network Communications

Socket Programming TCP UDP

Socket Programming for TCP and UDP

Types (Protocols) Associated functions Styles We will look at using sockets in C Java sockets are conceptually quite similar

Lecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005

SOCKETS. COMP750 Distributed Systems

Network Communication

Unix Network Programming

Processes communicating. Network Communication. Sockets. Addressing processes 4/15/2013

Socket Programming. Dr. -Ing. Abdalkarim Awad. Informatik 7 Rechnernetze und Kommunikationssysteme

CSC209H Lecture 9. Dan Zingaro. March 11, 2015

Socket Programming. CSIS0234A Computer and Communication Networks. Socket Programming in C

Hybrid of client-server and P2P. Pure P2P Architecture. App-layer Protocols. Communicating Processes. Transport Service Requirements

CS321: Computer Networks Socket Programming

Ports under 1024 are often considered special, and usually require special OS privileges to use.

A Client-Server Exchange

Session NM056. Programming TCP/IP with Sockets. Geoff Bryant Process software

Context. Distributed Systems: Sockets Programming. Alberto Bosio, Associate Professor UM Microelectronic Departement

CS321: Computer Networks Introduction to Application Layer

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Oral. Total. Dated Sign (2) (5) (3) (2)

SOCKET PROGRAMMING. What is a socket? Using sockets Types (Protocols) Associated functions Styles

CSE 124 Discussion Section Sockets Programming 10/10/17

Introduction to Socket Programming

The User Datagram Protocol

sottotitolo Socket Programming Milano, XX mese 20XX A.A. 2016/17 Federico Reghenzani

Department of Computer Science

Socket Programming(2/2)

Sockets 15H2. Inshik Song

NETWORK PROGRAMMING. Instructor: Junaid Tariq, Lecturer, Department of Computer Science

Client-server model The course that gives CMU its Zip! Network programming Nov 27, Using ports to identify services.

EEC-484/584 Computer Networks

UDP CONNECT TO A SERVER

CS 43: Computer Networks. 05: Socket Programming September 12-14, 2018

Programming with TCP/IP. Ram Dantu

Simple network applications using sockets (BSD and WinSock) Revision 1 Copyright Clifford Slocombe

CLIENT-SIDE PROGRAMMING

Socket Programming. Sungkyunkwan University. Hyunseung Choo Copyright Networking Laboratory

Chapter 6. The Transport Layer. Transport Layer 3-1

Lecture 2. Outline. Layering and Protocols. Network Architecture. Layering and Protocols. Layering and Protocols. Chapter 1 - Foundation

CS 3516: Computer Networks

CSCE 463/612 Networks and Distributed Processing Spring 2017

Network programming(i) Lenuta Alboaie

How do we Communicate? Introduction to Unix Network Programming. What does Alice do? What does Bob do? Two simplest networking programs

Tutorial on Socket Programming

Sockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

Sockets. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Client Server Computing

The BSD UNIX Socket Interface (CS 640 Lecture) Assignment 1. Interprocess Communication (IPC) Work Individually (no groups)

CS 640: Computer Networking

Christian Tschudin (basierend auf einem Foliensatz von C. Jelger und T. Meyer) Departement Mathematik und Informatik, Universität Basel

STUDY OF SOCKET PROGRAMMING

Lecture 5 Overview! Last Lecture! This Lecture! Next Lecture! I/O multiplexing! Source: Chapter 6 of Stevens book!

Introduction to Computer Networks

ECE 435 Network Engineering Lecture 2

UNIT IV- SOCKETS Part A

Network Socket Programming - 3 BUPT/QMUL

Announcements. CS 5565 Network Architecture and Protocols. Queuing. Demultiplexing. Demultiplexing Issues (1) Demultiplexing Issues (2)

Application Programming Interfaces

Network Socket Programming - 3 BUPT/QMUL

PA #2 Reviews. set_name, get_name, del_name. Questions? Will be modified after PA #4 ~

Part II: The Winsock API

Network Programming November 3, 2008

Group-A Assignment No. 6

2007 Microsoft Corporation. All rights reserved.

CS118 Discussion 1B, Week 1. Taqi Raza BUNCHE 1209B, Fridays 12:00pm to 1:50pm

Elementary TCP Sockets

1. Purpose. 2. Description Run-Time Issues Overview

Lecture 24. Thursday, November 19 CS 375 UNIX System Programming - Lecture 24 1

The TCP Protocol Stack

UNIX Sockets. Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E.

Socket Programming 2007/03/28

Lab 0. Yvan Petillot. Networks - Lab 0 1

Outline. Distributed Computing Systems. Socket Basics (1 of 2) Socket Basics (2 of 2) 3/28/2014

Topics for this Week

CPSC 213. Introduction to Computer Systems. Inter-Process Communication. Unit 2f

Socket Programming. What is a socket? Using sockets. Types (Protocols) Associated functions Styles

CSc 450/550 Computer Networks Network Architectures & Client-Server Model

ECE 435 Network Engineering Lecture 2

System Programming. Sockets

ICT 6544 Distributed Systems Lecture 5

JFx Joystick. June 21, Unrestricted Distribution. Revision 1.00

Network Programming Worksheet 2. Simple TCP Clients and Servers on *nix with C.

EECS122 Communications Networks Socket Programming. Jörn Altmann

What s an API? Do we need standardization?

Ch 7. Network Interface

Communication. Communication. Distributed Systems. Networks and protocols Sockets Remote Invocation Messages Streams. Fall /10/2001 DoCS

Socket programming in C

Internet protocol stack. Internetworking II: Network programming. April 20, UDP vs TCP. Berkeley Sockets Interface.

Introduction to Network Programming using C/C++

Internetworking II: Network programming. April 20, 2000

McGraw-Hill The McGraw-Hill Companies, Inc., 2000

TCP: Three-way handshake

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

Outline. Distributed Computer Systems. Socket Basics An end-point for a IP network connection. Ports. Sockets and the OS. Transport Layer.

31 ChamSys Remote Protocol Commands

CSE/EE 461 Lecture 14. Connections. Last Time. This Time. We began on the Transport layer. Focus How do we send information reliably?

Anatomy of a network. Chapter 3: Network and Communication. Transmission links. Representing data: bits and bytes. Representing data: Frames

Call DLL from Limnor Applications

Transcription:

EECS 123: Introduction to Real-Time Distributed Programming Lecture : IP, UDP, TCP, RPC, and Time Measurement This slide-set was prepared by the Teaching Assistant, P. Athreya. * Most of the slides in this set have been borrowed from Dr. Behrouz Forouzan who is the author of the book, 'TCP/IP Protocol', pub. by McGraw Hill, 2000, and placed various related slides on the Web. UCI DREAM Lab 1 1. OSI and TCP/IP UCI DREAM Lab 2

The OSI Model 3 On the sending end each layer adds a header to the passed on to it by the upper layer and passes it to the lower layer. Eventually the data is transmitted as binary electrical signals. On the receiving end the reverse is done and the headers are stripped while moving up the layers. 4

Layers in the TCP/IP Structure HTTP 5 The different layers use different kinds of addresses for communication. 6

2. Data link layer Protocols UCI DREAM Lab 7 Ethernet is a data link layer protocol that controls the access to the physical medium. However it introduces collisions which can be minimized using CSMA/CD protocol ( Carrier Sense Multiple Access / Collision Detection) 8

The Ethernet packet is the unit of transmission at the physical layer. The data field is an IP packet of at least 46 bytes. The frame is the unit without the preamble and SFD (Start of Frame Delimiter) size is 64 bytes. Frame is the unit at the data link layer. CRC is the checksum which contains error checking code for the entire packet. 9 The token ring is another medium access control protocol. It doesn t introduce collisions but involves a token that circulates from one user to another. Dead? 10

The token ring packet structure contains a modified token. The token itself is only 3 bytes and when a machine wants to transmit, it modifies the token by only 1 bit and follows it up with the destination address, etc. 11 3. IP Addressing UCI DREAM Lab 12

The IP address has 4 bytes and has the structure X.X.X.X where 0< X < 128 13 The IP addresses are classified into 5 different classes. Each class contains a group of address based on Netid which is assigned to a network. 14

15 4. Subnetting UCI DREAM Lab 16

Consider a Class B network as shown above. It is possible that the entire network is not used by a single organization. To facilitate networks smaller than the classes permit, this network can be subdivided as shown next. 17 So now smaller networks called subnetworks are possible from the same huge network as specified by a class. 18

So instead of only 2 parameters defining the network (netid & hostid) the subnetwork is defined by an additional parameter subnetid. However in practice both the netid and subnetid are replaced by the subnetmask. 19 Note that the subnet mask looks like an ip address and hence can have any value. E.G., a mask of 255.255.254.0 will result in the ip address set x.x.y.z where x.x is the first part of the netid, y is an even number from 0 to 255 and z is any number from 0 to 255. 20

A bitwise view of the subnetmask 21 Another subnet mask example. 22

5. Routing UCI DREAM Lab 23 Possible methods of delivery of IP packets. 24

Host A, Host B, R1, R2 are IP addresses. The figure shows 2 different methods of routing a. Routers keep the entire route to a destination in their table b. Routers only keep the neighboring routers in their table 25 6. Internet Protocol (IP) UCI DREAM Lab 26

IP packet with the header in detail. 27 IP packets may have to be fragmented as they are transported from source to destination. The numbers in red are the offsets of the fragments. 28

Offset calculation. The division by 8 is done because the offset is only 13 bits while the total length of the packet is expressed in 16 bits. 29 7. ARP and RARP UCI DREAM Lab 30

ARP = Address Resolution Protocol RARP = Reverse Address Resolution Protocol 31 32

The purpose of ARP is to get the physical address ( e.g., Ethernet address) of the machine to which an IP packet is to be sent. When the source calls ARP, then either the destination node or a router responsible for routing packets to that node (or network containing that node) will respond. 33 RARP is used by a node to obtain its own IP address when it boots. E.G., a node without a hard disk may need this => Every time the node starts, it asks a RARP server for its IP address. 34

8. User Datagram Protocol (UDP) UCI DREAM Lab 35 36

37 38

39 9. Transmission Control Protocol (TCP) In this course, we will use UDP only. Why? High-precision timing control in message communication is harder with TCP than with UDP. UCI DREAM Lab 40

s 41 s 42

s The sliding window protocol is used in the TCP for keeping track of acknowledged packets. 43 s Window size = 10 44

s Congestion control is done by adjusting the window size. Window size is increased when the congestion is less. 45 s Congestion is reduced by decreasing the window size. 46

s The acknowledgement contains the sequence number to be transmitted next. The figure shows retransmission of a window segment in TCP. 47 s 48

s 49 10. Domain Name System (DNS) UCI DREAM Lab 50

51 52

53 54

The client is looking for the IP address of mcgraw.com. 55 11. Socket Interface UCI DREAM Lab 56

Basic API Internet Address 57 Basic API in_addr This structure represents a host by its Internet address. typedef struct in_addr { union { struct { u_char s_b1, s_b2, s_b3, s_b4; } S_un_b; struct { u_short s_w1, s_w2; } S_un_w; u_long S_addr; } S_un; } in_addr; 58

Basic API inet_addr () unsigned long inet_addr ( const char * cp ); Converts a string containing an Standard Internet dotted address (e.g. 128.195.43.201) into an address in IN_ADDR structure format. inet_ntoa () Converts an Internet address (in IN_ADDR structure format) into a string in Internet standard dotted format. 59 Address IP port IP address Padding Family Used to specify a local or remote endpoint address to which to connect a socket 60

Basic API SOCKADDR_IN This structure is used to specify a local or remote endpoint address to which to connect a socket. struct sockaddr_in { short sin_family; // Address family (must be AF_INET) unsigned short sin_port; // IP port struct in_addr sin_addr; // IP address. char sin_zero [8]; // Padding to make structure // the same size as SOCKADDR. }; 61 62

Basic Utility Functions A u_short from host to TCP/IP network byte order These functions are needed because the byte order of the data stored in memory depends on the host machine architecture. 63 Basic Utility Functions void *memset (void *dest, int c, size_t count); // Sets the first count bytes of dest to the character c. // e.g. memset ( buffer, '*', 4 ); // size_t is same as unsigned integer. // dest - Pointer to destination. // count - Number of characters void *memcpy (void *dest, const void *src, size_t count); // Copies count bytes of src to dest. // dest - Pointer to destination. // src Pointer to source (buffer to copy from). // count - Number of characters to copy. int memcmp (const void *buf1, const void *buf2, size_t count); // Compares the first count bytes of buf1 and buf2 and returns a value indicating // their relationship. // buf1 Pointer to first buffer. buf2 - Pointer to second buffer. // count - Number of bytes. // Return Value < 0 means buf1 less than buf2 // Return Value = 0 means buf1 identical to buf2 // Return Value > 0 means buf1 greater than buf2 64

Basic Utility Functions MAKEWORD This macro creates an unsigned 16-bit integer by concatenating two specified unsigned character values. WORD MAKEWORD ( BYTE blow, // The low-order byte of the new short value BYTE bhigh // The high-order byte of the new short value ); 65 Basic API Retrieves host information corresp to a host name from a host DB 66

Basic API AF stands for Address Family AF_APPLETALK - value is 16 and stands for AppleTalk protocols AF_INET - value is 2 and stands for Inter-network (UDP, TCP, etc) 67 Basic API hostent Structure used to store information about a given host, such as host name, IP address, etc. typedef struct hostent { char * h_name; char ** h_aliases; short h_addrtype; short h_length; char ** h_addr_list; } hostent; h_name - Official name of the host (PC) h_aliases - Null-terminated array of alternate names. h_addrtype - Type of address being returned. (e.g. AF_INET) h_length - Length of each address, in bytes. h_addr_list - Null-terminated list of addresses for the host. Addresses are returned in network byte order. 68

Basic API socket 69 Basic API Socket () This (Windows Sockets) socket function creates a socket that is bound to a specific service provider. SOCKET socket ( int af, // address family specification int type, // type specification for the new socket // only two type specifications supported for // Windows Sockets 1.1 : // SOCK_STREAM (for TCP, value is 1) and // SOCK_DGRAM (for UDP, value is 2). int protocol // A particular protocol to be used with the socket // that is specific to the indicated address family ); 70

Basic API Setsockopt () This (Windows Sockets) setsockopt function sets a socket option. int setsockopt ( SOCKET s, // Identifies a socket int level, // Indicates the supported level of Socket. // The levels include SOL_SOCKET (value 0xffff) int optname, // Specifies the socket option. //E.G., SO_BROADCAST (value 0x0020) const char * optval, int optlen ); 71 Basic API Setsockopt () There are two types of socket options: Boolean options that enable or disable a feature or behavior Options that require an integer value or structure. To enable a Boolean option, optval points to a non-zero integer. To disable the option, optval points to an integer equal to zero. The optlen parameter should be equal to sizeof (int) for Boolean options. For other options, optval points to the an integer or structure that contains the desired value for the option, and optlen is the length of the integer or structure. 72

connect listen ; accept 73 Basic API (socket The bind function binds a newly created socket to a local address. Server uses this to associate a local address with a socket 74

Basic API bind () The (Windows Sockets) bind function associates a local address with a socket. int bind ( SOCKET s, // Identifies an unbound socket const struct sockaddr * name, // The address to assign to the socket. // ADDR_ANY or INADDR_ANY is specified, if you do // not care to which address the socket is bound to. // ADDR_ANY and INADDR_ANY stands for // (u_long) 0x00000000 int namelen // Length of the name ); 75 76

77 78

Basic API (socket Enters a listening mode listen () The (Windows Sockets) listen function places a socket in a state where it is listening for an incoming connection. int listen ( SOCKET s, int backlog // The maximum length of the queue of // pending connections ); 79 Basic API (socket Connect () A client uses this to connect to an existing socket The (Windows Sockets) connect function establishes a connection to a specified socket. int connect ( SOCKET s, // Identifies an unconnected socket const struct sockaddr * name, // Specifies the name of the socket to connect to int namelen // Length of the name parameter ); When the connect call completes successfully, it returns zero and the socket is ready to send/receive data. 80

Basic API (socket Permits an incoming connection attempt on a socket Accept () The (Windows Sockets) accept function accepts an incoming connection attempt on a socket. SOCKET accept ( SOCKET s, // Identifying a socket that has been placed in a // listening state with the listen function struct sockaddr * addr, // Optional pointer to a buffer that receives the // address of the connecting entity int * addrlen // Optional pointer to an integer that contains // the length of the address addr ); 81 Basic API Accept () The (Windows Sockets) accept function accepts an incoming connection attempt on a socket. SOCKET accept ( SOCKET s, // Identifying a socket that has been placed in a // listening state with the listen function struct sockaddr * addr, // Optional pointer to a buffer that receives the // address of the connecting entity int * addrlen // Optional pointer to an integer that contains // the length of the address addr ); 82

Basic API send () The (Windows Sockets) send function sends data on a connected socket. int send ( SOCKET s, // Identifies a connected socket const char * buf, // Specifies the buffer containing // the data to be transmitted int len, // The length of the data in buf int flags // An indicator specifying the way in which // the call is made. The default value is zero // which means that no options are set. ); 83 (socket Basic API sendto () Sends data to a specific destination The (Windows Sockets) sendto function sends data to a specific destination. int sendto ( SOCKET s, // Identifies a (possibly unconnected) socket const char * buf, // Specifies the buffer containing // the data to be transmitted int len, // The length of the data in buf. int flags, // Default : zero := No options are set. const struct sockaddr * to, //optional pointer to the address of the target socket int tolen // The size of the address in to ); 84

recv (socket Basic API recv () The (Windows Sockets) recv function receives data from a connected socket. int recv ( SOCKET s, // Identifies a connected socket char * buf, // Specifies a buffer for the incoming data int len, // The length of buf int flags // Flag specifying the way in which the call // is made. Default value is zero. ); 85 (socket Basic API recvfrom () The (Windows Sockets) recvfrom function receives a datagram and stores the source address. int recvfrom ( SOCKET s, // Identifies a bound socket char * buf, // Specifies a buffer for the incoming data int len, // The length of buf int flags struct sockaddr * from, // Optional pointer to a buffer that // will hold the source address int * fromlen // Optional pointer to the size of the from buffer ); 86

Basic API shutdown () The (Windows Sockets) shutdown function disables sends or receives on a socket. This function is used on all types of sockets to disable reception, transmission, or both. int shutdown ( SOCKET s, int how // how parameter is SD_RECEIVE (value is zero): // subsequent calls to the recv () function on the socket // will be disallowed. // how parameter is SD_SEND (value is One): // subsequent calls to the send () function are disallowed. // how is SD_BOTH (value is two): both send () and // recv () will be disabled. ); 87 Basic API Closesocket () The (Windows Sockets) closesocket function closes an existing socket. int closesocket ( SOCKET s ); Returns 0 if successful; -1 if error. 88

WSADATA This structure is used to store Windows Sockets initialization data returned by a call to WSAStartup. It contains data about the Winsock.dll implementation. struct WSAData { }; Basic API WORD wversion; // Version of Windows Sockets spec that caller uses WORD whighversion; // Highest version of Windows Sockets // specification that this DLL can support char szdescription [WSADESCRIPTION_LEN + 1]; // string into which the Windows Sockets DLL copies // a description of the Windows Sockets implementation char szsystemstatus [WSASYSSTATUS_LEN + 1]; // string into which Sockets DLL copies status unsigned short imaxsockets; // Max number of sockets which a // single process can open unsigned short imaxudpdg; // Size, in bytes, of the largest UDP // datagram that can be sent or received by a WinSock appl. char * lpvendorinfo; // Long pointer to a vendor-specific data structure 89 90

12. TCP/IP Sample Program UCI DREAM Lab 91 s /****************************/ //sockserver.cpp /***************************/ #include <winsock2.h> #include <stdio.h> #include <iostream.h> void main() { SOCKET sendsock; SOCKADDR_IN sendsockaddr; int port = 4031; WSADATA Data; int status = WSAStartup (MAKEWORD(1, 1), &Data); // Initialize Winsock.dll vers 1.1. // This function must be the first Windows Sockets // function called by an application or DLL. if ( status!= 0 ) { printf ("ERROR: WSAStartup unsuccessful. We couldn't find a Winsock DLL (version 1.1)\n"); return; 92 }

s memset (&sendsockaddr, 0, sizeof(sendsockaddr)); sendsockaddr.sin_port = htons (port); sendsockaddr.sin_family = AF_INET; sendsockaddr.sin_addr.s_addr = htonl (ADDR_ANY); // Finds a local IP addr sendsock = socket (AF_INET, SOCK_STREAM, 0); // A TCP socket is created. if ( sendsock == INVALID_SOCKET ) // INVALID_SOCKET is 0. { printf ("ERROR: socket creation unsuccessful\n"); } status = bind (sendsock, (LPSOCKADDR) &sendsockaddr, sizeof (sendsockaddr)); // The socket is bound to a local address. if ( status == SOCKET_ERROR ) printf ("ERROR: bind unsuccessful %d\n ", WSAGetLastError()); 93 s listen (sendsock,0); // The number of pending connections // allowed is set to zero. printf ("accepting...\n"); SOCKET sendsock2 = accept (sendsock,0,0); // A blocking call if ( sendsock2 == INVALID_SOCKET ) printf ("ERROR: accept unsuccessful %d\n", WSAGetLastError()); printf ("sending...\n"); Sleep (2000); Two-way int send_data = 100; int numsnt = send (sendsock2, (char*) &send_data, sizeof(send_data), 0); // The data is sent through the socket and send () // returns the number of bytes sent. if ( numsnt == SOCKET_ERROR ) cout << "ERROR: send unsuccessful\n" << WSAGetLastError() << endl cout << "data sent = " << send_data << endl; } Sleep (3000); 94

s /****************************/ //sockclient.cpp /***************************/ #include <winsock2.h> #include <stdio.h> #include <iostream.h> void main() { SOCKET recvsock; SOCKADDR_IN recvsockaddr; int port = 4031; WSADATA Data; int status = WSAStartup (MAKEWORD(1, 1), &Data); // Initialize Winsock.dll if ( status!= 0 ) { printf ("ERROR: WSAStartup unsuccessful. We couldn't find a Winsock DLL (version 1.1)\n"); return; } 95 s memset (&recvsockaddr, 0, sizeof (recvsockaddr) ); recvsockaddr.sin_port = htons (port); recvsockaddr.sin_family = AF_INET; recvsockaddr.sin_addr.s_addr = inet_addr ("128.195.164.147"); // inet_addr function converts the IP address into // in_addr struct format. recvsock = socket (AF_INET, SOCK_STREAM, 0); // A TCP socket is created. if ( recvsock == INVALID_SOCKET ) { printf ("ERROR: socket creation unsuccessful\n"); } 96

printf ("connecting...\n"); s status = connect (recvsock, (LPSOCKADDR) &recvsockaddr, sizeof (recvsockaddr) ); if ( status == SOCKET_ERROR ) printf ("ERROR: connect unsuccessful %d\n", WSAGetLastError() ); int recv_data; printf ("receiving...\n"); int numrcv = recv (recvsock, (char*) &recv_data, sizeof (recv_data), 0); if ( numrcv == SOCKET_ERROR numrcv!= sizeof(recv_data)) { printf ("ERROR: recvfrom unsuccessful\n"); int errorcode = WSAGetLastError(); printf ("Error Code = %d\n", errorcode ); } cout << "data received = " << recv_data << endl; } Sleep(5000); 97 13. UDP Sample Program UCI DREAM Lab 98

/****************************/ //socksendudp.cpp /***************************/ #include <winsock2.h> #include <stdio.h> #include <iostream.h> void main() { SOCKET sendsock; SOCKADDR_IN sendsockaddr; SOCKET recvsock; SOCKADDR_IN recvsockaddr; int port1 = 4031; int port2 = 4032; WSADATA Data; int status = WSAStartup (MAKEWORD(1, 1), &Data); // Init Winsock.dll if ( status!= 0 ) printf ("ERROR: WSAStartup unsuccessful. We couldn't find a Winsock DLL (version 1.1)\n"); 99 memset (&sendsockaddr, 0, sizeof (sendsockaddr) ); sendsockaddr.sin_port = htons (port1); sendsockaddr.sin_family = AF_INET; sendsockaddr.sin_addr.s_addr = htonl (INADDR_BROADCAST); // INADDR_BROADCAST stands for 0xffffffff sendsock = socket (AF_INET, SOCK_DGRAM, 0); if ( sendsock == INVALID_SOCKET ) { printf ("ERROR: socket creation unsuccessful\n", WSAGetLastError());} int enable = 1; // Permit sending of broadcast msgs status = setsockopt (sendsock, SOL_SOCKET, SO_BROADCAST, (char *) &enable, sizeof(int)); // The socket is set as a broadcast socket if ( status == SOCKET_ERROR ) printf ("ERROR: bind unsuccessful\n", WSAGetLastError()); 100

memset (&recvsockaddr, 0, sizeof(recvsockaddr)); recvsockaddr.sin_port = htons (port2); recvsockaddr.sin_family = AF_INET; recvsockaddr.sin_addr.s_addr = htonl (INADDR_ANY); recvsock = socket (AF_INET, SOCK_DGRAM, 0); // A UDP socket is created. if ( recvsock == INVALID_SOCKET ) { printf ("ERROR: socket creation unsuccessful\n", WSAGetLastError()); return; } status = bind (recvsock, (LPSOCKADDR) &recvsockaddr, sizeof (recvsockaddr) ); // The socket is bound to a local address. if ( status == SOCKET_ERROR ) printf ("ERROR: bind unsuccessful\n", WSAGetLastError()); printf ("sending data...\n"); Sleep(2000); 101 } int send_data = 100; int numsnt = sendto ( sendsock, (char*) &send_data, sizeof (send_data),0, (LPSOCKADDR) &sendsockaddr, sizeof (sendsockaddr) ); if ( numsnt == SOCKET_ERROR ) printf ("ERROR: Broadcast sendto unsuccessful\n", WSAGetLastError()); cout << "data sent = " << send_data << endl; printf ("receiving acknowlegdement...\n"); int recv_ack; int numrcv = recvfrom (recvsock, (char*) &recv_ack, sizeof (recv_ack), 0, NULL, NULL); if ( numrcv == SOCKET_ERROR numrcv!= sizeof(recv_ack)) printf ("ERROR: recvfrom unsuccessful\n", WSAGetLastError()); cout << "acknowlegdement received = " << recv_ack << endl; Sleep(3000); 102

/****************************/ //sockrecvudp.cpp /***************************/ #include <winsock2.h> #include <stdio.h> #include <iostream.h> void main () { SOCKET sendsock; SOCKADDR_IN sendsockaddr; SOCKET recvsock; SOCKADDR_IN recvsockaddr; int port1 = 4031; int port2 = 4032; WSADATA Data; int status = WSAStartup (MAKEWORD(1, 1), &Data); // Init Winsock.dll if ( status!= 0 ) { printf ("ERROR: WSAStartup unsuccessful. We couldn't find a Winsock DLL (version 1.1)\n"); return; } memset (&sendsockaddr, 0, sizeof(sendsockaddr)); sendsockaddr.sin_port = htons (port2); sendsockaddr.sin_family = AF_INET; sendsockaddr.sin_addr.s_addr = htonl (INADDR_BROADCAST); 103 sendsock = socket(af_inet, SOCK_DGRAM, 0); if ( sendsock == INVALID_SOCKET ) { printf("error: socket creation unsuccessful\n", WSAGetLastError()); } int enable = 1; // Permit sending of broadcast msgs status = setsockopt (sendsock, SOL_SOCKET, SO_BROADCAST, (char*) &enable, sizeof(int)); if ( status == SOCKET_ERROR ) printf ("ERROR: bind unsuccessful\n", WSAGetLastError()); memset (&recvsockaddr, 0, sizeof(recvsockaddr)); recvsockaddr.sin_port = htons (port1); recvsockaddr.sin_family = AF_INET; recvsockaddr.sin_addr.s_addr = htonl (INADDR_ANY); recvsock = socket (AF_INET, SOCK_DGRAM, 0); if ( recvsock == INVALID_SOCKET ) { printf ("ERROR: socket creation unsuccessful\n", WSAGetLastError()); return; } status = bind (recvsock, (LPSOCKADDR) &recvsockaddr, sizeof(recvsockaddr)); if ( status == SOCKET_ERROR ) printf ("ERROR: bind unsuccessful\n", WSAGetLastError()); 104

printf ("receiving data...\n"); int recv_data; int numrcv = recvfrom (recvsock, (char*) &recv_data, sizeof(recv_data), 0, NULL, NULL); if ( numrcv == SOCKET_ERROR numrcv!= sizeof(recv_data)) printf ("ERROR: recvfrom unsuccessful\n", WSAGetLastError()); cout << "data received = " << recv_data << endl; printf ("sending acknowlegdement...\n"); Sleep(2000); int send_ack = 101; int numsnt = sendto ( sendsock, (char*) &send_ack, sizeof (send_ack),0, (LPSOCKADDR) &sendsockaddr, sizeof (sendsockaddr)); if ( numsnt == SOCKET_ERROR ) printf ("ERROR: Broadcast sendto unsuccessful\n", WSAGetLastError()); cout << "acknowlegdement sent = " << send_ack << endl; } Sleep(3000); 105 14. Remote Procedure Call (RPC) UCI DREAM Lab 106

Remote Procedure Call (RPC) Make it appear to users as though a client directly calls a procedure located in a remote server program. The client and server each have their own address spaces Each has its own memory resource allocated to data used by the procedure. 107 RPC Calling Sequence The client application calls a local stub procedure instead of the actual code implementing the procedure. Client stubs are compiled and linked with the client application. Retrieves the required parameters from the client address space. Translates the parameters as needed into a standard NDR format for transmission over the network. Calls functions in the RPC client run-time library to send the request and its parameters to the server. The server performs the following steps to call the remote procedure. The server RPC run-time library functions accept the request and call the server stub procedure. The server stub retrieves the parameters from the network buffer and converts them from the network transmission format to the format the server needs. The server stub calls the actual procedure on the server. 108

When the remote procedure is complete, output parameters and a return value are sent to the client. The remote procedure returns its data to the server stub. The server stub converts output parameters to the format required for transmission over the network and returns them to the RPC run-time library functions. The server RPC run-time library functions transmit the data on the network to the client computer. The client completes the process by accepting the data over the network and returning it to the calling function. The client RPC run-time library receives the remote-procedure return values and returns them to the client stub. The client stub converts the data from its NDR to the format used by the client computer. The stub writes data into the client memory and returns the result to the calling program on the client. The calling procedure continues as if the procedure had been called on the same computer. RPC Result Return 109 Remote Procedure Call (RPC) Looks like a function call Combines Request and Reply En- / De-codes and transmits parameters and return values Example RPC mechanisms Sun RPC (RFC 1050), Xerox Courier One-way RPC does not involve return values from the remote server. Is it a slightly higher-level mechanism than a request message? More often than not, one-way RPC is more useful than two-way RPC is in RT distributed computing. Going a step further results in a remote method call among distributed computing objects Java RMI CORBA 110

Remote Procedure Call (RPC) A narrow view: Single thread of control split between two processes A broader view: Non-blocking service request (SR) is allowed as an instance of RPC. No shared global variables Pragmatic to recognize the possibility of network or remote server failing Use of timeouts is useful. Usually an order-of-magnitude slower than a local function call In some environments, authentication may be involved. 111 112

113 15. Time Measurement UCI DREAM Lab 114

The system can be measured using the following system call GetSystemTime (SYSTEMTIME* lpsystemtime) This is Win32 API useful on windows based systems. Similar calls are available for other OSs. This function returns the current system time and stores into the SYSTEMTIME structure. typedef struct _SYSTEMTIME { WORD wyear; WORD wmonth; WORD wdayofweek; WORD wday; WORD whour; WORD wminute; WORD wsecond; WORD wmilliseconds; } SYSTEMTIME, *PSYSTEMTIME; Note that the time returned has millisecond level precision. 115 Using this function one can measure the time taken to complete a synchronous Remote Procedure Call as follows : GetSystemTime (systemtime_before_call); Result = Remote_Procedure_Call (possible_parameters); GetSystemTime (systemtime_after_call); RPC_time = Difference_of (systemtime_after_call, systemtime_before_call); Note the difference of the time is not a direct subtraction since these are structures. So before the subtraction, Convert the SYSTEMTIME structure to a FILENAME structure. Copy the resulting FILETIME structure to a ULARGE_INTEGER structure. Use normal subtraction on the ULARGE_INTEGER value. 116

typedef struct _FILETIME { DWORD dwlowdatetime; DWORD dwhighdatetime; } FILETIME, *PFILETIME; typedef union _ULARGE_INTEGER { struct { DWORD LowPart; DWORD HighPart; }; ULONGLONG QuadPart; } ULARGE_INTEGER, *PULARGE_INTEGER; 117 In order to measure the time taken to send/receive messages on the network, first the round trip time is measured as follows Process 1 systemtime_before_send systemtime_before_receive 1 2 Process 2 (on another machine) Process 2 is waiting to receive. As soon as it receives a message, it sends a reply. 118

Process 1 : GetSystemTime (systemtime_before_send); send (message); // send message to Process 2 either // through a TCP or UDP connection receive (reply); // receive reply from Process 2 either // through a TCP or UDP connection GetSystemTime (systemtime_after_receive); Round_trip_time = Difference_of (systemtime_after_receive, systemtime_before_send); One_way_trip_time = Round_trip_time/2; Process 2 : receive (message); // wait to receive message from Process 2 send (reply); // on receiving the message reply to // Process 1 The one_way_trip_time is approximately the time taken to send/receive a message. Of course this value is not always true but several measurements of this value can be used to estimate the average and worst case values. 119 References [For00] Behrouz Forouzan, 'TCP/IP Protocol', pub. by McGraw Hill, 2000. http://www.hill.com/library/publications/tcpip.shtml http://sources.redhat.com/ecos/docs-latest/tcpip/tcpip.4.html http://msdn.microsoft.com/library/default.asp?url=/library/enus/sysinfo/time_5gh1.asp http://msdn.microsoft.com/library/default.asp?url=/library/enus/sysinfo/time_827m.asp 120