CS 351 Week Advanced UNIX Programming: Rochkind, Marc J. 1. To learn about System Interprocess Communication (IPC). 2. To learn about Sockets.

Similar documents
CS 351 Week 15. Course Review

Interprocess Communication

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

EEC-484/584 Computer Networks

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

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

Programming with TCP/IP. Ram Dantu

Introduction to Socket Programming

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

Socket Programming for TCP and UDP

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

Group-A Assignment No. 6

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

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

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

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

Programming Internet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

A Socket Example. Haris Andrianakis & Angelos Stavrou George Mason University

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

TCP: Three-way handshake

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

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

Systems software design NETWORK COMMUNICATIONS & RPC SYSTEMS

STUDY OF SOCKET PROGRAMMING

Network Communication

Tutorial on Socket Programming

What s an API? Do we need standardization?

Client Server Computing

CSE 124 Discussion Section Sockets Programming 10/10/17

Interprocess Communication Mechanisms

Interprocess Communication Mechanisms

Java Networking (sockets)

Computer Network Lab, SS Fachgebiet Technische Informatik, Joachim Zumbrägel. Overview. Sockets. Sockets in C.

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

Unix Network Programming

TCP Networking in Java. Some reminders

Chapter 4: Processes

Outline. Operating Systems. Socket Basics An end-point for a IP network connection. Ports. Network Communication. Sockets and the OS

Redes de Computadores (RCOMP)

Interprocess Communication Mechanisms

shared storage These mechanisms have already been covered. examples: shared virtual memory message based signals

MSc Integrated Electronics Networks Assignment. Investigation of TCP/IP Sockets and Ports. Gavin Cameron

Socket Programming TCP UDP

CS 428/528 Computer Networks Lecture 01. Yan Wang

Sockets 15H2. Inshik Song

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

CS 43: Computer Networks. 07: Concurrency and Non-blocking I/O Sep 17, 2018

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

CptS 360 (System Programming) Unit 17: Network IPC (Sockets)

Elementary TCP Sockets

CLIENT-SIDE PROGRAMMING

Overview. Last Lecture. This Lecture. Daemon processes and advanced I/O functions

SOCKETS. COMP750 Distributed Systems

Redesde Computadores(RCOMP)

Socket Programming. #In the name of Allah. Computer Engineering Department Sharif University of Technology CE443- Computer Networks

Motivation of VPN! Overview! VPN addressing and routing! Two basic techniques for VPN! ! How to guarantee privacy of network traffic?!

CPS 214: Computer Networks. Slides by Adolfo Rodriguez

Agenda. Before we start: Assignment #1. Routing in a wide area network. Protocols more concepts. Internetworking. Congestion control

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

CS4700/CS5700 Fundamentals of Computer Networking

System Programming. Sockets

Socket Programming. Sungkyunkwan University. Hyunseung Choo Copyright Networking Laboratory

Socket Programming(2/2)

Application Programming Interfaces

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

CS 640: Computer Networking

CSC209H Lecture 9. Dan Zingaro. March 11, 2015

Memory-Mapped Files. generic interface: vaddr mmap(file descriptor,fileoffset,length) munmap(vaddr,length)

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

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

CSE 333 Section 8 - Client-Side Networking

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

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

Review. Preview. Closing a TCP Connection. Closing a TCP Connection. Port Numbers 11/27/2017. Packet Exchange for TCP Connection

Internet Technology 2/1/2016

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

Networked Applications: Sockets. Goals of Todayʼs Lecture. End System: Computer on the ʻNet. Client-server paradigm End systems Clients and servers

A Client-Server Exchange

UNIX Sockets. COS 461 Precept 1

Networks. Practical Investigation of TCP/IP Ports and Sockets. Gavin Cameron

CSE 43: Computer Networks Structure, Threading, and Blocking. Kevin Webb Swarthmore College September 14, 2017

Introduction to Socket Programming

Networked Applications: Sockets. End System: Computer on the Net

Introduction for SPI mapping Service Discovery Interoperability Testing. 20, Sep PWG Fumio Nagasaka

Sockets. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

UNIT IV- SOCKETS Part A

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

A. Basic Function Calls for Network Communications

CS321: Computer Networks Introduction to Application Layer

CS September 2017

Interprocess Communication Mechanisms

Interprocess Communication Mechanisms

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

CS631 - Advanced Programming in the UNIX Environment Interprocess Communication II

Sistemas Operativos /2016 Support Document N o 1. Files, Pipes, FIFOs, I/O Redirection, and Unix Sockets

Programming Ethernet with Socket API. Hui Chen, Ph.D. Dept. of Engineering & Computer Science Virginia State University Petersburg, VA 23806

CS 3516: Computer Networks

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

JAVA - NETWORKING (SOCKET PROGRAMMING)

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

Transcription:

CS 351 Week 11 Reading: 1. Advanced UNIX Programming: Rochkind, Marc J. Objectives: 1. To learn about System Interprocess Communication (IPC). 2. To learn about Sockets. Concepts: 1. Interprocess Communication 2. Sockets 3. Pipes Outline: 1. Interprocess Communication 2. Sockets a. What Are Sockets b. Functions i. Creation ii. Binding iii. Closing iv. Connecting v. Sending vi. Receiving vii. Listening viii. Accepting 3. Pipes a. Creating b. Example 4. Sockets on UNIX Reference: 1. Socket Abstraction and Interprocess Communication, Ramamurthy B, 2007, http://www.cse.buffalo.edu/~bina/cse421/fall2003/socketsnov13.ppt 2. http://www.geocities.com/siliconvalley/bay/6879/chat.html CS 351 Week 11 Page 1

1. Interprocess Communication CS 351: Week 11 Lecture Notes - Typical applications today consist of many cooperating processes either on the same host or on different hosts. - For example, consider a client-server application. How to share (large amounts of) data? - How to share files and avoid contention issues? - We want a general mechanism that will work for processes irrespective of their location. IPC: Purpose - Data Transfer - Sharing Data - Event Notification - Process Control IPC at different Levels: - Process Level- Pipes - OS Level- Sockets - Plain Language Level- Distriubuted System Methods 2. IPC using Sockets - Sockets are used if we want to communicate between processes that have no common ancestors. - Sockets are used when we want communication between processes that are not necessarily on the same host. - Sockets use names to refer to one another. What are Sockets? - Socket is an abstraction for an end point of communication that can be manipulated with a file descriptor. - It is an abstract object from which messages are sent and received. - Sockets are created within a communication domain just as files are created within a file system. - A communication domain is an abstraction introduced to bundle common properties of processes communicating through sockets. Example: UNIX domain, internet domain. Sockets and Ports: - About 216 ports are available for use by user processes. CS 351 Week 11 Page 2

- Socket is associated with a protocol. - IPC is transmitting a message between sockets in one process to a socket in another process. - Messages sent to particular IP and port number can be received by the process whose socket is associated with that IP and port number. - Processes cannot share ports with other processes within the computer. Can receive messages on different ports. Socket Names: - Applications refer to sockets with their names. - Within communication domains sockets are referred by addresses. - Name to address translation is done outside the OS. Socket Types: - The format in which an address is specified is according to a domain: o AF_UNIX (address format of UNIX) - a path name within the file system, o AF_INET (internet format): network address, port number etc. - Communication style: stream, datagram, raw or sequenced packets o Stream: reliable, error-free, connection-oriented comm. o Datagram: Connectionless, unreliable, message boundaries preserved. Sockets: Functions - Creating a Socket o socket system call create a socket on demand. o int socket(int domain, int type, int protocol) Domain: PF_INET (Internet), PF_UNIX (local) Type: SOCK_STREAM, SOCK_DGRAM, SOCK_RAW Protocol: 0 usually for IP (see /etc/protocols for details) - Binding a Socket o A socket is created without any association to local or destination address. It is possible to bind the socket to a specific host and in it a specific port number. o int bind(int socket struct sockaddr *addr int addr_len) - Closing a socket o close (socid); closes the specified socket. This is done by a process or thread when it no longer needs the socket connection. o close(int socket) - Connecting CS 351 Week 11 Page 3

o A socket is created in an unconnected state, which means that the socket is not associated with any destination. o An application program should call connect to establish a connection before it can transfer data thru reliable stream socket. For datagrams connect is not required but recommended. o int connect(int socket, struct sockaddr *addr, int addr_len) - Sending o Five different system calls : send, sendto, sendmsg, write, writev o send, write and writev work only with connected sockets. No parameter for destination address. Prior connect should be present for communication. o int send(int socket, char *buf, int blen, int flags) - Receiving o Five different calls are available: read, readv, recv, recvfrom, recvmsg o read, readv, and recv are for connection-oriented comm. o int recv(int socket, char *buf, int blen, int flags) - Listening o To avoid having protocols reject incoming request, a server may have to specify how many messages need to be queued until it has time to process them. o Example: listen(socket,length); - Accepting o Wait for the call. o int accept(int socket, struct sockaddr *addr, int addr_len) 3. Pipes - Provides interprocess communication channel - Processes must be on the same machine - Used mostly for filters - A filter is a process that reads from stdin and writes to stdout - Pipe is a communication channel abstraction Process A can write to one end using write system call Process B can read from the other end using read system call - System call - int pipe( int fd[2] ); return 0 upon success 1 upon failure fd[0] is open for reading fd[1] is open for writing CS 351 Week 11 Page 4

- Two coordinated processes created by fork can pass data to each other using a pipe. 4. Sockets in Unix: - When a program calls fork, the newly created process inherits access to all open sockets. - For threads socket identifiers should be defined in the common address space or passed as parameters. - include files : <socket.h>, <un.h> or <in.h>, and other related header files. - When linking add a -lsocket option besides. Lab Exercise: Chat servers connect two or more clients so that the input of one client is output to all other clients. Attempt number zero of a chat server that reads a line of text from the keyboard and prints to the screen is below. No networking is done so the server isn't really a server but does illustrate some of the general structure of a chat server. Implement a chat server that provides network connection with a client? Solution: Java: import java.awt.*; import java.io.*; import java.net.*; import java.util.*; public class Nets { public static void main(string argv[]) { kickoff kickoffobject = new kickoff(); // end of Nets class class kickoff extends Thread { DataInputStream dis; client[] clientarray = new client[100]; int i = 0; int x = 0; String name; kickoff() { start(); public void run() { CS 351 Week 11 Page 5

server serverobject = new server(); void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of kickoff class class server extends Thread { read_from_connection readobj; int num = 1; Thread readthread; Socket sock; ServerSocket listen; static int i = 0; static Vector v = new Vector(); server() { start(); public void run() { System.out.println("Server thread started"); try { listen = new ServerSocket(4321); // listen = new ServerSocket(8090); while(true) { readobj = new read_from_connection(listen.accept(), this); System.out.println("connection accepted"); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) {System.out.println("Error connecting to host"); synchronized void add_to_vector(read_from_connection obj) { v.addelement(obj); CS 351 Week 11 Page 6

synchronized void remove_from_vector(read_from_connection obj) { v.removeelement(obj); synchronized boolean duplicate_name(read_from_connection obj) { read_from_connection readobj; for (int i = 0; i < v.size(); i++) { readobj = (read_from_connection)v.elementat(i); if (readobj.name.equals(obj.name)) return true; return false; synchronized void broadcast_message(string message) { read_from_connection readobj; for (int i = 0; i < v.size(); i++) { readobj = (read_from_connection)v.elementat(i); readobj.pout.println(message); synchronized void list_names(printstream pout, String name) { String line; read_from_connection readobj; pout.println("welcome " + name); "); if (v.size() > 0 ) pout.println("the following people are in the chat room: else pout.println("you are alone in the chat room"); line = ""; int cnt = 0; for (int i = 0; i < v.size(); i++) { CS 351 Week 11 Page 7

readobj = (read_from_connection)v.elementat(i); if (line.equals("")) line += readobj.name; else line += ", " +readobj.name; cnt++; if (cnt == 10) { pout.println(line); line = ""; cnt = 0; if (line!= "") pout.println(line); void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of server class class read_from_connection extends Thread { Socket sock; InputStream in; OutputStream out; DataInputStream din; PrintStream pout; int hours; int minutes; int seconds; String name = " "; String request; server serverobj; read_from_connection readobj; read_from_connection(socket sock, server serverobj) { this.sock = sock; this.serverobj = serverobj; start(); public void run() { CS 351 Week 11 Page 8

System.out.println("read_from_connection thread started"); try { in = sock.getinputstream(); out = sock.getoutputstream(); pout = new PrintStream(out); din = new DataInputStream(in); pout.println("you have connected to the chat server, type something to begin"); request = din.readline(); format_message(); if (serverobj.duplicate_name(this)) { pout.println("name already in use - try another"); pout.println("disconecting..."); stop(); sock.close(); room"); serverobj.list_names(pout, name); serverobj.add_to_vector(this); serverobj.broadcast_message(name + " has entered the chat pause(1000); // pause before sending serverobj.broadcast_message(format_message()); while(true) { request = din.readline(); serverobj.broadcast_message(format_message()); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) { serverobj.remove_from_vector(this); if (name.equals(" ") == false) { serverobj.broadcast_message(name + " has left the chat room"); stop(); String format_message() { String text; String hoursout; String hourss; CS 351 Week 11 Page 9

String minutess; String secondss; String name; int a; int b; int c; text = ""; name = ""; Date date = new Date(); hours = date.gethours(); hourss = Integer.toString(hours); if (hours <= 9) hourss = "0"+hoursS; minutes = date.getminutes(); minutess = Integer.toString(minutes); if (minutes <= 9) minutess = "0"+minutesS; seconds = date.getseconds(); secondss = Integer.toString(seconds); if (seconds <= 9) secondss = "0"+secondsS; hoursout = "[" + hourss + ":" + minutess + ":" + secondss +"]"; a = request.indexof(' '); if (a == -1) return hoursout + " " + name + " - " + text; b = request.indexof(' ', a + 1); if (a == -1) return hoursout + " " + name + " - " + text; name = request.substring(a + 1,b); this.name = name; c = request.length(); text = request.substring(b + 1, c - 1); return hoursout + " " + name + " - " + text; void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of read_from_connection CS 351 Week 11 Page 10

class client extends Thread { DataInputStream dis; Socket sock; PrintStream pout; InputStream in; OutputStream out; DataInputStream din; client() { start(); public void run() { System.out.println("client thread started"); try { // sock = new Socket("161.178.105.233", 4321); // work // sock = new Socket("161.178.105.220", 8888); // mike sock = new Socket("161.178.121.1", 4321); // unix server System.out.println("connection made"); in = sock.getinputstream(); out = sock.getoutputstream(); pout = new PrintStream(out); din = new DataInputStream(in); while(true) { String request = din.readline(); System.out.println(request); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) {System.out.println("Error connecting to host"); // end of client class CS 351 Week 11 Page 11