Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM



Similar documents
Network Programming using sockets

Data Communication & Networks G

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

Goal: learn how to build client/server application that communicate using sockets. An interface between application and network

Java Network. Slides prepared by : Farzana Rahman

Chapter 2: Application layer

Data Communications & Networks. Session 2 Main Theme Application Layer. Dr. Jean-Claude Franchitti

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

Socket Programming. Announcement. Lectures moved to

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

Network Programming with Sockets. Process Management in UNIX

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Network Communication

Introduction to Socket programming using C

Lesson: All About Sockets

Socket Programming in C/C++

TCP/IP - Socket Programming

ELEN 602: Computer Communications and Networking. Socket Programming Basics

Division of Informatics, University of Edinburgh

Internet Applications & Socket Programming

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

Application Development with TCP/IP. Brian S. Mitchell Drexel University

Network Programming TDC 561

Socket Programming. Request. Reply. Figure 1. Client-Server paradigm

Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute

ICT SEcurity BASICS. Course: Software Defined Radio. Angelo Liguori. SP4TE lab.

Networks. Inter-process Communication. Pipes. Inter-process Communication

Introduction to Socket Programming Part I : TCP Clients, Servers; Host information

Socket Programming. Kameswari Chebrolu Dept. of Electrical Engineering, IIT Kanpur

Tutorial on Socket Programming

SSC - Communication and Networking Java Socket Programming (II)

IP Network Layer. Datagram ID FLAG Fragment Offset. IP Datagrams. IP Addresses. IP Addresses. CSCE 515: Computer Network Programming TCP/IP

Socket Programming. Srinidhi Varadarajan

Application Architecture

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Chapter 11. User Datagram Protocol (UDP)

Operating Systems Design 16. Networking: Sockets

Computer Networks/DV2 Lab

Creating a Simple, Multithreaded Chat System with Java

Socket-based Network Communication in J2SE and J2ME

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users

Implementing Network Software

Socket UDP. H. Fauconnier 1-1. M2-Internet Java

NS3 Lab 1 TCP/IP Network Programming in C

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

Network/Socket Programming in Java. Rajkumar Buyya

Java Programming: Sockets in Java

The exam has 110 possible points, 10 of which are extra credit. There is a Word Bank on Page 8. Pages 7-8 can be removed from the exam.

Network Programming. Writing network and internet applications.

Socket Programming in Java

Transport Layer Services Mul9plexing/Demul9plexing. Transport Layer Services

IT304 Experiment 2 To understand the concept of IPC, Pipes, Signals, Multi-Threading and Multiprocessing in the context of networking.

NETWORK PROGRAMMING IN JAVA USING SOCKETS

The POSIX Socket API

Writing a C-based Client/Server

Writing Client/Server Programs in C Using Sockets (A Tutorial) Part I. Session Greg Granger grgran@sas. sas.com. SAS/C & C++ Support

Objectives of Lecture. Network Architecture. Protocols. Contents

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

q Connection establishment (if connection-oriented) q Data transfer q Connection release (if conn-oriented) q Addressing the transport user

CS335 Sample Questions for Exam #2

Lab 4: Socket Programming: netcat part

TCP/IP Fundamentals. OSI Seven Layer Model & Seminar Outline

Porting applications & DNS issues. socket interface extensions for IPv6. Eva M. Castro. ecastro@dit.upm.es. dit. Porting applications & DNS issues UPM

Building a Multi-Threaded Web Server

Mail User Agent Project

Transport Layer Protocols

Socket = an interface connection between two (dissimilar) pipes. OS provides this API to connect applications to networks. home.comcast.

Abstract Stream Socket Service

Generalised Socket Addresses for Unix Squeak

UNIX Sockets. COS 461 Precept 1

Introduction to Computer Networks

Communicating with a Barco projector over network. Technical note

Computer Networks. Chapter 5 Transport Protocols

Computer Networks - Xarxes de Computadors

Overview. Socket Programming. Using Ports to Identify Services. UNIX Socket API. Knowing What Port Number To Use. Socket: End Point of Communication

Implementing and testing tftp

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Programmation Systèmes Cours 9 UNIX Domain Sockets

Lecture 28: Internet Protocols

Socket programming. Complement for the programming assignment INFO-0010

[Prof. Rupesh G Vaishnav] Page 1

INTRODUCTION UNIX NETWORK PROGRAMMING Vol 1, Third Edition by Richard Stevens

TFTP Usage and Design. Diskless Workstation Booting 1. TFTP Usage and Design (cont.) CSCE 515: Computer Network Programming TFTP + Errors

Network layer" 1DT066! Distributed Information Systems!! Chapter 4" Network Layer!! goals: "

First Workshop on Open Source and Internet Technology for Scientific Environment: with case studies from Environmental Monitoring

Chapter 2: outline. 2.6 P2P applications 2.7 socket programming with UDP and TCP

Kiwi SyslogGen. A Freeware Syslog message generator for Windows. by SolarWinds, Inc.

Assignment 4 Solutions

Computer Networks Practicum 2015

What is CSG150 about? Fundamentals of Computer Networking. Course Outline. Lecture 1 Outline. Guevara Noubir noubir@ccs.neu.

Introduction To Computer Networking

Transcription:

Socket Programming Rohan Murty Hitesh Ballani Last Modified: 2/8/2004 8:30:45 AM Slides adapted from Prof. Matthews slides from 2003SP Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API introduced in BSD4.1 UNIX, 1981 Sockets are explicitly created, used, released by applications client/server paradigm two types of transport service via socket API: unreliable datagram reliable, byte streamoriented socket a host-local, applicationcreated/owned, OS-controlled interface (a door ) into which application process can both send and receive messages to/from another (remote or local) application process Sockets Socket: a door between application process and end-end-transport protocol (UCP or TCP) controlled by application developer controlled by operating system process socket kernel buffers, variables host or server internet process socket kernel buffers, variables host or server controlled by application developer controlled by operating system Languages and Platforms Socket API is available for many languages on many platforms: C, Java, Perl, Python, *nix, Windows, Socket Programs written in any language and running on any platform can communicate with each other! Writing communicating programs in different languages is a good exercise

Decisions Socket programming with TCP Before you go to write socket code, decide Do you want a TCP-style reliable, full duplex, connection oriented channel? Or do you want a UDP-style, unreliable, message oriented channel? Will the code you are writing be the client or the server? : you assume that there is a process already running on another machines that you need to connect to. Server: you will just start up and wait to be contacted must contact server server process must first be running server must have created socket (door) that welcomes client s contact 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 Frees up incoming port allows server to talk with multiple clients application viewpoint TCP provides reliable, in-order transfer of bytes ( pipe ) between client and server Pseudo code TCP client socket, connectsocket Do an active connect specifying the IP address and port number of server Read and Write Data Into connectsocket to Communicate with server Close connectsocket Pseudo code TCP server socket (serversocket) Bind socket to a specific port where clients can contact you Register with the kernel your willingness to listen that on socket for client to contact you Loop Accept new connection (connectsocket) Read and Write Data Into connectsocket to Communicate with client Close connectsocket End Loop Close serversocket

Example: Java client (TCP) Example: Java client (TCP), cont. input stream client socket, connect to server output stream attached to socket import java.io.*; import java.net.*; class TCP { public static void main(string argv[]) throws Exception { String sentence; String modifiedsentence; BufferedReader infromuser = new BufferedReader(new InputStreamReader(System.in)); Socket clientsocket = new Socket("hostname", 6789); DataOutputStream outtoserver = new DataOutputStream(clientSocket.getOutputStream()); input stream attached to socket Send line to server Read line from server BufferedReader infromserver = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = infromuser.readline(); outtoserver.writebytes(sentence + '\n'); modifiedsentence = infromserver.readline(); System.out.println("FROM SERVER: " + modifiedsentence); clientsocket.close(); Example: Java server (TCP) welcoming socket at port 6789 Wait, on welcoming socket for contact by client input stream, attached to socket import java.io.*; import java.net.*; class TCPServer { public static void main(string argv[]) throws Exception { String clientsentence; String capitalizedsentence; ServerSocket welcomesocket = new ServerSocket(6789); while(true) { Socket connectionsocket = welcomesocket.accept(); BufferedReader infrom = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Example: Java server (TCP), cont output stream, attached to socket Read in line from socket DataOutputStream outto = new DataOutputStream(connectionSocket.getOutputStream()); clientsentence = infrom.readline(); capitalizedsentence = clientsentence.touppercase() + '\n'; Write out line outto.writebytes(capitalizedsentence); to socket End of while loop, loop back and wait for another client connection

/server socket interaction: TCP (Java) Server (running on hostid) create socket, port=x, for incoming request: welcomesocket = ServerSocket() TCP wait for incoming connection request connection setup connectionsocket = welcomesocket.accept() read request from connectionsocket write reply to connectionsocket close connectionsocket create socket, connect to hostid, port=x clientsocket = Socket() send request using clientsocket read reply from clientsocket close clientsocket Queues We just saw a simple example, with one socket on the server handling incoming connections While the server socket is busy, incoming connections are stored in a queue until it can accept them Most systems maintain a queue length between 5 and 50 Once the queue fills up, further incoming connections are refused until space in the queue opens up This is a problem in a situation where our server has to handle many concurrent incoming connections. Example: HTTP servers Solution? Use concurrency Concurrent TCP Servers Threadpools Benefit comes in ability to hand off processing to another process Parent process creates the door bell or welcome socket on well-known port and waits for clients to request connection When a client does connect, fork off a child process to handle that connection so that parent process can return to waiting for connections as soon as possible Multithreaded server: same idea, just spawn off another thread rather than a full process Threadpools? serversocket 2 Thread Pool Worker Threads 3 1 2.1

Socket programming with UDP Pseudo code UDP server UDP: very different mindset than TCP no connection just independent messages sent no handshaking sender explicitly attaches IP address and port of destination server must extract IP address, port of sender from received datagram to know who to respond to 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 socket Bind socket to a specific port where clients can contact you Loop (Receive UDP Message from client x)+ (Send UDP Reply to client x)* Close Socket Pseudo code UDP client socket Loop (Send Message To Well-known port of server)+ (Receive Message From Server) Close Socket Example: Java client (UDP) input stream client socket Translate hostname to IP address using DNS import java.io.*; import java.net.*; class UDP { public static void main(string args[]) throws Exception { BufferedReader infromuser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientsocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] senddata = new byte[1024]; byte[] receivedata = new byte[1024]; String sentence = infromuser.readline(); senddata = sentence.getbytes();

Example: Java client (UDP), cont. Example: Java server (UDP) datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server DatagramPacket sendpacket = new DatagramPacket(sendData, senddata.length, IPAddress, 9876); clientsocket.send(sendpacket); DatagramPacket receivepacket = new DatagramPacket(receiveData, receivedata.length); clientsocket.receive(receivepacket); String modifiedsentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedsentence); clientsocket.close(); datagram socket at port 9876 space for received datagram Receive datagram import java.io.*; import java.net.*; class UDPServer { public static void main(string args[]) throws Exception { DatagramSocket serversocket = new DatagramSocket(9876); byte[] receivedata = new byte[1024]; byte[] senddata = new byte[1024]; while(true) { DatagramPacket receivepacket = new DatagramPacket(receiveData, receivedata.length); serversocket.receive(receivepacket); Example: Java server (UDP), cont /server socket interaction: UDP Get IP addr port #, of sender datagram to send to client Write out datagram to socket String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.getport(); String capitalizedsentence = sentence.touppercase(); senddata = capitalizedsentence.getbytes(); DatagramPacket sendpacket = new DatagramPacket(sendData, senddata.length, IPAddress, port); serversocket.send(sendpacket); End of while loop, loop back and wait for another datagram Server (running on hostid) create socket, port=x, for incoming request: serversocket = DatagramSocket() read request from serversocket write reply to serversocket specifying client host address, port umber create socket, clientsocket = DatagramSocket(), address (hostid, port=x, send datagram request using clientsocket read reply from clientsocket close clientsocket

UDP Server vs Server has a well-known port number initiates contact with the server Less difference between server and client code than in TCP Both client and server bind to a UDP socket Not accept for server and connect for client send to the well-known server port; server extracts the client s address from the datagram it receives TCP vs UDP TCP can use read/write (or recv/send) and source and destination are implied by the connection; UDP must specify destination for each datagram Sendto, recvfrm include address of other party TCP server and client code look quite different; UDP server and client code vary mostly in who sends first Byte ordering Byte-Order Transformation Big Endian byte-order The byte order for the TCP/IP protocol suite is big endian.

Some Definitions Socket address structure Internet Address Structure struct in_addr { in_addr_t s_addr; ; in_addr_t is defined as a long on linux machines, implying 32 bit addresses! Address Transformation Socket Types

Server 1. transport endpoint for incoming connection request: socket() 2. Assign transport endpoint an address: bind( ) 3. Announce willing to accept connections: listen( ) 4. Block and Wait for incoming request: accept( ) 5. Wait for a packet to arrive: read ( ) 6. Formulate reply (if any) and send: write( ) 7. Release transport endpoint: close( ) 1. transport endpoint: socket( ) 2. Assign transport endpoint an address (optional): bind( ) 3. Determine address of server 4. Connect to server: connect( ) 4. Formulate message and send: write ( ) 5. Wait for packet to arrive: read( ) 6. Release transport endpoint: close( ) CONNECTION-ORIENTED SERVICE Connectionless Service (UDP) Server 1. transport endpoint: socket() 2. Assign transport endpoint an address: bind() 3. Wait for a packet to arrive: recvfrom() 4. Formulate reply (if any) and send: sendto() 5. Release transport endpoint: close() 1. transport endpoint: socket() 2. Assign transport endpoint an address (optional): bind() 3. Determine address of server 4. Formulate message and send: sendto() 5. Wait for packet to arrive: recvfrom() 6. Release transport endpoint: close() Procedures That Implement The Socket API Creating and Deleting Sockets fd=socket(protofamily, type, protocol) s a new socket. Returns a file descriptor (fd). Must specify: the protocol family (e.g. TCP/IP) the type of service (e.g. STREAM or DGRAM) the protocol (e.g. TCP or UDP) close(fd) Deletes socket. For connected STREAM sockets, sends EOF to close connection. Procedures That Implement The Socket API Putting Servers on the Air bind(fd,laddress,laddresslen) Used by server to establish port to listen on. When server has >1 IP addrs, can specify IF_ANY, or a specific one listen (fd, queuesize) Used by connection-oriented servers only, to put server on the air Queuesize parameter: how many pending connections can be waiting

(cont ) afd = accept (lfd, caddress, caddresslen) Used by connection-oriented servers to accept one new connection There must already be a listening socket (lfd) Returns afd, a new socket for the new connection, and The address of the caller (e.g. for security, log keeping. etc.) Procedures That Implement The Socket API How s Communicate with Servers? connect (fd, saddress, saddreslen) Used by connection-oriented clients to connect to server There must already be a socket bound to a connection-oriented service on the fd There must already be a listening socket on the server You pass in the address (IP address, and port number) of the server. Used by connectionless clients to specify a default send to address Subsequent sends don t have to specify a destination address Procedures That Implement The Socket API How s Communicate with Servers? (TCP) intwrite (fd, data, length) Used to send data write is the normal write function; can be used with both files and sockets intread (fd, data,length) Used to receive data parameters are similar! NOTE : both functions can return a value less than the length Procedures That Implement The Socket API How s Communicate with Servers(UDP) int sendto (fd, data, length, flags, destaddress, addresslen) Used to send data. Connectionless socket, so we need to specify the dest address int recvfrom(fd,data,length,flags,srcaddress,addresslen) Used to receive data parameters are similar, but in reverse

Concurrent Server: TCP (C/C++) Server (running on hostid) create socket, port=x, for incoming request: socket(),bind(),listen() Non-blocking I/O By default, accept(), recv(), etc block until there s input What if you want to do something else while you re waiting? We can set a socket to not block (i.e. if there s no input an error will be returned) or, we can tell the kernel to let us know when a socket is ready, and deal with it only then non-blocking/select The host uses select() to get the kernel to tell it when the peer has sent a message that can be recv() d Can specify multiple sockets on which to wait -- select returns when one or more sockets are ready -- operation can time out! Java vs C Java hides more of the details new ServerSocket of Java = socket, bind and listen of C new Socket hides the getbyname (or gethostbyname) of C; Unable to hide this in the UDP case though Socket API first in C for BSD; more options and choices exposed by the interface than in Java?

PROJECT 1 : BASIC SOCKETS (CONT ) AIM: Write a program (referred to as the IP box) that opens four sockets, two TCP and two UDP 2 TCP SOCKETS : 1. A receive-config socket : IP BOX acts as a Server (must be bound to a port you have to find, and the interface IP address) 2. A send-config socket : IP BOX acts a reciever 2 UDP SOCKETS App -- acts as the interface between the IP layer and the application Iface represents the network interface Both must be bound to an used port and the interface address IP BOX OPERATION Send-config sockets connects to the Test Box and sends a ready-to-test command The Test Box then connects to recv-config socket and send a \n terminated command which must be echoed The Test Box then sends UDP packets to app and iface sockets which must be echoed (Note : If the Test Box does not receive your echo, it retransmits the packet) (cont ) On receiving both the echoes, the Test Box sends a send-stat command to the send-config socket The IP box sends a list-of-stats The Test Box then sends an exit message ( during final test, this will have a 40 character hex string representing a hashed timestamp, which your program must RECORD!)