The Sockets Library and Concepts Rudra Dutta CSC 230 - Spring 2007, Section 001.

Slides:



Advertisements
Similar presentations
Sockets: Network IPC Internet Socket UNIX Domain Socket.
Advertisements

Socket Programming Application Programming Interface.
Sockets Programming CS144 Review Session 1 April 4, 2008 Ben Nham.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Quick Overview. 2 ISO/OSI Reference Model Application Application Presentation Presentation Session Session Transport Transport Network Network Data Link.
Socket Programming: a Primer Socket to me!. Feb. 23, 2001EE122, UCB2 Why does one need sockets? application network protocol sockets network.
1 Socket Interfaces Professor Jinhua Guo CIS527 Fall 2003.
תקשורת באינטרנט 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.
Tutorial 8 Socket Programming
Socket Addresses. Domains Internet domains –familiar with these Unix domains –for processes communicating on the same hosts –not sure of widespread use.
CSE/EE 461 Getting Started with Networking. Basic Concepts  A PROCESS is an executing program somewhere.  Eg, “./a.out”  A MESSAGE contains information.
SOCKETS Lecture #3. The Socket Interface Funded by ARPA (Advanced Research Projects Agency) in Developed at UC Berkeley Objective: to transport.
UNIX Sockets COS 461 Precept 1. Clients and Servers Client program – Running on end host – Requests service – E.g., Web browser Server program – Running.
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
UNIX Sockets COS 461 Precept 1.
Client Software Design Objectives: Understand principles of C/S design, with focus on clients Review Windows implementations of Socket functions.
1 Programming with TCP/IP Ram Dantu. 2 Client Server Computing r Although the Internet provides a basic communication service, the protocol software cannot.
1 Programming with TCP/IP by Armin R. Mikler. 2 Client Server Computing r Although the Internet provides a basic communication service, the protocol software.
ECE 4110 – Internetwork Programming Client-Server Model.
Sockets and intro to IO multiplexing. Goals We are going to study sockets programming as means to introduce IO multiplexing problem. We will revisit socket.
Operating Systems Chapter 9 Distributed Communication.
Network Programming Tutorial #9 CPSC 261. A socket is one end of a virtual communication channel Provides network connectivity to any other socket anywhere.
Socket Programming. Introduction Sockets are a protocol independent method of creating a connection between processes. Sockets can be either – Connection.
CS345 Operating Systems Φροντιστήριο Άσκησης 2. Inter-process communication Exchange data among processes Methods –Signal –Pipe –Sockets.
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.
 Wind River Systems, Inc Chapter - 13 Network Programming.
Chapter 2 Applications and Layered Architectures Sockets.
The Socket Interface Chapter 22. Introduction This chapter reviews one example of an Application Program Interface (API) which is the interface between.
1 Socket Programming r What is a socket? r Using sockets m Types (Protocols) m Associated functions m Styles m We will look at using sockets in C.
Remote Shell CS230 Project #4 Assigned : Due date :
CS 158A1 1.4 Implementing Network Software Phenomenal success of the Internet: – Computer # connected doubled every year since 1981, now approaching 200.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
TELE202 Lecture 15 Socket programming 1 Lecturer Dr Z. Huang Overview ¥Last Lecture »TCP/UDP (2) »Source: chapter 17 ¥This Lecture »Socket programming.
UNIT8: SOCKETS Topics Introduction to sockets Socket Addresses
University of Calgary – CPSC 441.  A socket is an interface between the application and the network (the lower levels of the protocol stack)  The application.
UNIX Sockets COS 461 Precept 1. Socket and Process Communication The interface that the OS provides to its networking subsystem application layer transport.
Introduction to Socket
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 3.1 Internet Applications Ch. 28,… (Client-Server Concept, Use of Protocol Ports, Socket API)
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 Lab 1 1CS Computer Networks.
1 Sockets Programming Socket to me!. 2 Network Application Programming Interface (API) The services provided by the operating system that provide the.
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
CS 6401 Introduction to Computer Networks 09/21/2010 Outline - UNIX sockets - A simple client-server program - Project 1 - LAN bridges and learning.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
Introduction to Sockets
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
Read() recv() connection establishment Server (connection-oriented protocol) blocks until connection from client Client socket() bind() listen() accept()
2: Application Layer 1 Socket Programming UNIX Network Programming, Socket Programming Tutorial:
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
UNIX Sockets Outline UNIX sockets CS 640.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
Lecture 3 TCP and UDP Sockets CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
1 Socket Interface. 2 Client-Server Architecture The client is the one who speaks first Typical client-server situations  Client and server on the same.
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.
Socket Programming in C
Socket Interface 1 Introduction 11 Socket address formats 2 API 12 13
Tutorial on Socket Programming
Transport layer API: Socket Programming
UNIX Sockets Outline Homework #1 posted by end of day
Socket Programming in C
Socket Programming.
Socket Programming(1/2)
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Socket Programming Neil Tang 09/08/2008
Internet Networking recitation #8
Socket Programming What is a socket? Using sockets Types (Protocols)
CSI 4118 – UNIVERSITY OF OTTAWA
Presentation transcript:

The Sockets Library and Concepts Rudra Dutta CSC Spring 2007, Section 001

Copyright Rudra Dutta, NCSU, Spring API for Network Apps Interface between TCP/IP and applications only loosely specified The standards suggest the functionality (not the details) – allocate resources for communication – specify communication endpoints – initiate a connection (client) or wait for incoming connection (server) – send or receive data – terminate a connection gracefully – handle error conditions – etc.

Copyright Rudra Dutta, NCSU, Spring Unix File I/O Program calls open() to initiate input or output – returns a file descriptor (small, positive integer) Calls to read() or write() to transfer data – with the file descriptor as an argument Once I/O operations are completed, the program calls close() Other relevant system calls: lseek(), ioctl() – (these are not used in the Sockets API)

Copyright Rudra Dutta, NCSU, Spring Unix File I/O Example Roughly the same for sockets, except for setup int fd; char buf[256]; fd = open("a.txt", ORDWR | O_CREAT); write(fd, buf, sizeof(buf)); close(fd);

Copyright Rudra Dutta, NCSU, Spring Socket API Introduced in 1981 by BSD 4.1 – implemented as system calls – originally only Unix but WinSock almost the same Mainly, two services – datagram (UDP) – stream (TCP)

Copyright Rudra Dutta, NCSU, Spring The Socket Abstraction Provides an endpoint for communication – also provides buffering – sockets are not bound to specific addresses at the time of creation Identified by small integer, the socket descriptor Flexibility – functions that can be used with many different protocols – programmer specifies the type of service required, rather than the protocol number – a generic address structure

Copyright Rudra Dutta, NCSU, Spring Endpoint Addresses Each socket association has five components – protocol – local address – local port – remote address – remote port protocol: used by socket() local address, port: bind() remote address, port: connect(), sendto()

Copyright Rudra Dutta, NCSU, Spring Creating A Socket Parameters – domain: PF_INET – type: SOCK_DGRAM, SOCK_STREAM, SOCK_RAW – protocol: usually = 0 (i.e., default for type) Example #include … if ((s = socket(PF_INET, SOCK_STREAM, 0) < 0) perror("socket"); int s = socket(domain, type, protocol);

Copyright Rudra Dutta, NCSU, Spring After Creating A Socket (cont'd)

Copyright Rudra Dutta, NCSU, Spring Generic Address Structure Each protocol family defines its own address representation For each protocol family there is a corresponding address family – (e.g., PF_INET  AF_INET, PF_UNIX  AF_UNIX) Generalized address format: – struct sockaddr { u_charsa_len; /* total length */ u_short sa_family; /* type of address */ char sa_data[14]; /* value of address */ };

Copyright Rudra Dutta, NCSU, Spring Socket Addresses, Internet Style #include struct in_addr { u_long s_addr; /* 32-bit host address */ }; struct sockaddr_in { u_char sin_len; /* total length */ short sin_family; /* AF_INET */ u_short sin_port; /* network byte order */ struct in_addr sin_addr; /* network address */ char sin_zero[8]; /* unused */ };

Copyright Rudra Dutta, NCSU, Spring Binding the Local Address Used primarily by servers to specify their well-known port Optional for clients – normally, system chooses a “random” local port Use INADDR_ANY to allow the socket to receive datagrams sent to any of the machine's IP addresses int bind(int s, struct sockaddr *addr, int addrlen);

Copyright Rudra Dutta, NCSU, Spring Binding the Local Address (cont'd) … sin.sin_family = AF_INET; sin.sin_port = htons(6000); /* if 0:system chooses */ sin.sin_addr.s_addr = INADDR_ANY; /* allow any interface */ if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) /* error function here */

Copyright Rudra Dutta, NCSU, Spring After Binding the Local Address

Copyright Rudra Dutta, NCSU, Spring Establish a Connection Queue Only used for stream sockets Used by connection-oriented servers to place a socket in passive mode – makes it ready to accept incoming connections – the remote port # / IP address of the socket = 0 (any port, any IP address) Allows backlog pending connections to be waiting for accept() int listen(int s, int backlog);

Copyright Rudra Dutta, NCSU, Spring Accepting Connection Requests Executed by connection-oriented server, after listen() – blocks until a connection request from a client arrives Returns a new, unique socket ( newsock ) for data exchange with the client – this new socket is for the connection with port # / IP address of the client as the remote port and IP address – this new socket must be closed when the client and server are through communicating newsock = accept(int s, struct sockaddr *clientaddr, int *clientaddrlen);

Copyright Rudra Dutta, NCSU, Spring Accepting Connection Requests The original socket s (with 0 as remote address) remains open – when a TCP segment arrives for this host/port, and no existing socket has a remote IP address / port # = to the source IP address/port of the segment, the segment will be sent to the original socket s Must call accept() again to obtain the next connection request

Copyright Rudra Dutta, NCSU, Spring Accepting Connections (cont'd)

Copyright Rudra Dutta, NCSU, Spring Connecting To A Server Binds a permanent destination to a socket – uses 3-way handshake to establish connection (active open) As a side effect, it chooses a local endpoint (IP address and port number) if the socket does not have one – Cients normally let the system choose their (ephemeral) port # May fail – host not listening to port – timeout int connect(int s, struct sockaddr *servername, int servernamelen);

Copyright Rudra Dutta, NCSU, Spring Client-Server Interaction: TCP

Copyright Rudra Dutta, NCSU, Spring Sending and Receiving Data Types – read(), write() – recv(), send() – recvfrom(), sendto() Options: flags which modify action of a call – read() and write() may not specify options Notes – block size read may not = block size written – read from stream may read fewer bytes than requested

Copyright Rudra Dutta, NCSU, Spring Sending Data Flags control transmission – E.g., specify urgent data Write might not be able to write all buflen bytes (on a nonblocking socket) int write(int s, char* buf, int buflen); int send(int s, char* buf, int buflen, int flags);

Copyright Rudra Dutta, NCSU, Spring Receiving Data Flags control reception, e.g., – out-of-band data – message look-ahead Reminder! – block size read may not = block size written – read from stream may read fewer bytes than requested If the other end has closed the connection, and there is no buffered data, reading from a TCP socket returns 0 to indicate EOF int read(int s, char* buf, int buflen); int recv(int s, char* buf, int buflen, int flags);

Copyright Rudra Dutta, NCSU, Spring Closing A Connection Actions – decrements reference count for socket – terminates communication gracefully and removes socket when reference count = 0 Problem – server does not know if client has additional requests – client does not know if server has additional data to send int close(int s);

Copyright Rudra Dutta, NCSU, Spring Partially Closing A Connection Direction – 0 to close the input (reading) end – 1 to close the output (writing) end – 2 for both Used by client to specify it has no more data to send, without deallocating connection Server receives an EOF signal on read() or recv(), can then close connection after sending its last response int shutdown(int s, int direction);

Copyright Rudra Dutta, NCSU, Spring Datagram Communication First 4 arguments same as in send() Sends buflen bytes in buffer buf to location to, with options flags (usually 0) The return value of sendto() indicates how much data was accepted by the O.S. for sending as a datagram – not how much data made it to the destination – there is no error condition that indicates the destination did not get the data! int sendto(int s, char *buf, int buflen, int flags, struct sockaddr *to, int tolen);

Copyright Rudra Dutta, NCSU, Spring Datagram Communication (cont’d) First 4 arguments same as in recv() Receives up to len bytes into buffer buf – returns number of bytes received, 0 on EOF – if buf is not large enough, any extra data is lost forever recvfrom blocks until datagram available, by default Sets from to source address of data – sending replies is easy int recvfrom(int s, char *buf, int buflen, int flags, struct socaddr *from, int fromlen);

Copyright Rudra Dutta, NCSU, Spring Connected vs. Unconnected UDP Sockets UDP sockets can be connected or unconnected – in connected mode, client uses connect() to specify a remote endpoint – convenient to interact with a specific server repeatedly connect(): only records the remote address, does not initiate any packet exchange write(): sends a single message to the server read(): returns one complete message

Copyright Rudra Dutta, NCSU, Spring Closing UDP Sockets close() – releases the resources associated with a socket – does not inform the remote endpoint that the socket is closed shutdown() – can be used to mark socket as unwilling to transfer data in the direction specified – does not send any message to the other side

Copyright Rudra Dutta, NCSU, Spring Client-Server Interaction: UDP Contrast with TCP

Copyright Rudra Dutta, NCSU, Spring Byte Ordering Representation

Copyright Rudra Dutta, NCSU, Spring Byte-Order Transformations

Copyright Rudra Dutta, NCSU, Spring Byte-Order Transformations (cont’d) Byte ordering is a function of machine architecture – Intel: little-endian – Sparc, PowerPC: big-endian – Network order: big-endian Functions – u_long m = ntohl(u_long m) network-to-host byte order, 32 bit – u_long m = htonl(u_long m) host-to-network byte order, 32 bit – ntohs(), htons() short (16 bit) Be safe; it never hurts to use, and it improves portability

Copyright Rudra Dutta, NCSU, Spring Address Conversions Internally, IP addresses are represented as 32-bit integers int addr = inet_addr(char *str) addr : network byte order, str : dotted decimal form char *str = inet_ntoa(struct in_addr in)

Copyright Rudra Dutta, NCSU, Spring Obtaining Information About Hosts, etc. struct hostent *hptr; /* includes host address in binary */ hptr = gethostbyname(char *name); Ex.: gethostbyname(“ struct hostent *hptr; hptr = gethostbyaddr(char *addr, int addrlen, int addrtype); Ex.: gethostbyaddr(&addr, 4, AF_INET);

Copyright Rudra Dutta, NCSU, Spring Obtaining Information int inet_addr(char *dotdecimal); Ex.: sin_addr = inet_addr(“ ”); struct servent *sptr; /* includes port and protocol */ sptr = getservbyname(char *name, char *proto); Ex.: getservbyname(“smtp”, “tcp”); struct protoent *pptr; /* includes protocol number */ pptr = getprotobyname(char *name); Ex.: getprotobyname(“tcp”);

Copyright Rudra Dutta, NCSU, Spring Example of Connection Establishment // host - name of host to which connection is desired // service - service associated with the desired port // transport - name of transport protocol to use ("tcp“, "udp") memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; /* Map service name to port number */ if ( pse = getservbyname(service, transport) ) sin.sin_port = pse->s_port; else if ((sin.sin_port = htons((unsigned short)atoi(service))) == 0) errexit("can't get \"%s\" service entry\n", service);

Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Map host name to IP address, allowing for dotted decimal */ if ( phe = gethostbyname(host) ) memcpy(&sin.sin_addr, phe->h_addr, phe->h_length); else if ((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE ) errexit("can't get \"%s\" host entry\n", host); /* Map transport protocol name to protocol number */ if ( (ppe = getprotobyname(transport)) == 0) errexit("can't get \"%s\" protocol entry\n", transport);

Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Use protocol to choose a socket type */ if (strcmp(transport, "udp") == 0) type = SOCK_DGRAM; else type = SOCK_STREAM; /* Allocate a socket */ s = socket(PF_INET, type, ppe->p_proto); if (s < 0) errexit("can't create socket: %s\n", strerror(errno));

Copyright Rudra Dutta, NCSU, Spring Example (cont’d) /* Connect the socket */ if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) errexit("can't connect to %s.%s: %s\n", host, service, strerror(errno)); return s;