1 Introduction to Computer Networks Ilam University By: Dr. Mozafar Bag Mohammadi Sockets.

Slides:



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

Socket Programming CS3320 Fall 2010.
Sockets: Network IPC Internet Socket UNIX Domain Socket.
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.
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.
1 Netcomm Recitation 1: Sockets Communication Networks Recitation 1.
1 Netcomm Sockets Communication Networks Recitation 1.
1 Comnet Recitation 2 - Sockets Communication Networks Recitation 2.
1 Socket Interfaces Professor Jinhua Guo CIS527 Fall 2003.
Tutorial 8 Socket Programming
1 Netcomm Sockets Communication Networks Recitation 2.
Programming with Berkeley Sockets Presented by Chris GauthierDickey Written by Daniel Stutzbach (I think!) for CIS 432/532 Useful References: ● man pages.
Introduction to Socket Programming April What is a socket? An interface between application and network –The application creates a socket –The socket.
Introduction to Project 1 Web Client and Server Jan 2006.
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.
1 Socket Programming r What is a socket? r Using sockets m Types (Protocols) m Associated functions m Styles.
Socket Programming Based on tutorial prepared by EUISOK CHUNG CS3320 Spring2008.
CPSC 441 TUTORIAL – JANUARY 18, 2012 TA: MARYAM ELAHI INTRODUCTION TO SOCKET PROGRAMMING WITH C.
Lecture 2 Socket Programming Spring 2004
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
Operating Systems Chapter 9 Distributed Communication.
CS345 Operating Systems Φροντιστήριο Άσκησης 2. Inter-process communication Exchange data among processes Methods –Signal –Pipe –Sockets.
Sirak Kaewjamnong Computer Network Systems
 Wind River Systems, Inc Chapter - 13 Network Programming.
1 Internet Socket programming Behzad Akbari. 2 Sharif University of Technology, Kish Island Campus What is an API? API – stands for Application Programming.
Chapter 2 Applications and Layered Architectures Sockets.
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.
CS x760 Computer Networks1 Socket Programming. CS 6760 Computer Networks2 Socket Programming  What is a socket?  Using sockets  Types (Protocols) ‏
Computer Networks : TP1 Prof. Dr. Amine Berqia and Prof. Dr. Fernando Lobo {bamine,
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.
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.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
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.
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
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
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 m Note:
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.
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.
@Yuan Xue CS 283Computer Networks Spring 2013 Instructor: Yuan Xue.
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 Presented By : Divya Sharma.
Socket Programming What is a socket? Using sockets Types (Protocols)
CSCE 313 Network Socket MP8 DUE: FRI MAY 5, 2017
Socket Programming in C
Review: TCP Client-Server Interaction
Introduction to Computer Networks
Imam Ahmad Trinugroho, ST., MMSI
Transport layer API: Socket Programming
Socket Programming What is a socket? Using sockets Types (Protocols)
Socket Programming.
Chapter 2 Application Layer
Socket Programming What is a socket? Using sockets Types (Protocols)
Socket Programming(1/2)
Socket Programming What is a socket? Using sockets Types (Protocols)
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Internet Networking recitation #8
Socket Programming What is a socket? Using sockets Types (Protocols)
Presentation transcript:

1 Introduction to Computer Networks Ilam University By: Dr. Mozafar Bag Mohammadi Sockets

2 Outline r What is a socket? r Types of sockets r Uses of sockets r Socket function r Byte order r Dealing with blocking r Some useful function

3 r Goal- Communication between two processes r They use interface/services from the transport layer. The interface is called Application Programming Interface, API. Client process Server process TCP/UDP IP Ethernet Adaptor Socket API Socket programming

4 What is a socket? r An API between application and network m Define an “end- point” for communication m The application creates a socket m The socket type dictates the style of communication reliable vs. best effort connection-oriented vs. connectionless m Initiate and accept a connection r Once configured the application can m pass data to the socket for network transmission m receive data from the socket (transmitted through the network by some other host) m Terminate a connection gracefully r Berkeley Sockets are the most common (from BSD Unix)

5 Two essential types of sockets r SOCK_STREAM m a.k.a. TCP m reliable delivery m in-order guaranteed m connection-oriented m bidirectional r SOCK_DGRAM m a.k.a. UDP m unreliable delivery m no order guarantees m no notion of “connection” – app indicates dest. for each packet m can send or receive App socket Dest. App socket D1 D3 D2 Q: why have type SOCK_DGRAM ?

6 Client- Server communication (UDP) socket() to create socket bind() to a receiving port recvfrom () sendto() socket() to create scoket bind() to any port recvfrom () sendto () server client

7 Client- Server communication (TCP) socket() bind() to a receiving port listen () to socket Accept() connection socket() bind() to any port connect () to server send() recv() send() recv() server client

8 Example  A generic server (FTP) :Wait for connections on a port When a client connection comes in, loop: – Read in the client’s request – Read data from a file – Send the data to the client – Disconnect when we have reached EOF  A generic client, high level : Connect to a given server loop: – Send a request to the server – Read server’s response – Read server’s data – Disconnect when we have reached EOF

9 Socket Creation in C: socket r int s = socket(domain, type, protocol);  s : socket descriptor, an integer (like a file-handle)  domain : integer, communication domain e.g., PF_INET (IPv4 protocol) – typically used, PF_UNIX  type : communication type SOCK_STREAM : reliable, 2-way, connection-based service SOCK_DGRAM : unreliable, connectionless, other values: need root permission, rarely used, or obsolete  protocol : specifies protocol (see file /etc/protocols for a list of options) - usually set to 0  NOTE: socket call does not specify where data will be coming from, nor where it will be going to – it just creates the interface!

10 A Socket-eye view of the Internet r Each host machine has an IP address r When a packet arrives at a host medellin.cs.columbia.edu ( ) cluster.cs.columbia.edu ( , , , ) newworld.cs.umass.edu ( )

11 Ports Port 0 Port 1 Port r Each host has 65,536 ports r Some ports are reserved for specific apps m 20,21: FTP m 23: Telnet m 80: HTTP m see RFC 1700 (about 2000 ports are reserved) r A socket provides an interface to send data to/from the network through a port

Well-known ports 12

13 Addresses, Ports and Sockets r Like apartments and mailboxes m You are the application m Your apartment building address is the address m Your mailbox is the port m The post-office is the network m The socket is the key that gives you access to the right mailbox (one difference: assume outgoing mail is placed by you in your mailbox!)

14 The bind function r associates and (can exclusively) reserves a port for use by the socket r int status = bind(sockid, &addrport, size);  status : error status, = -1 if bind failed  sockid : integer, socket descriptor  addrport : struct sockaddr, m struct sockaddr_in { u_char sin_family; /* Address Family */ u_short sin_port; /* Port number */ struct in_addr sin_addr; /* IP address */ char sin_zero[8]; /* unused */ };  size : the size (in bytes) of the addrport structure

15 Skipping the bind  SOCK_DGRAM : m if only sending, no need to bind. The OS finds a port each time the socket sends a pkt m if receiving, need to bind  SOCK_STREAM : m destination determined during conn. setup m don’t need to know port sending from (during connection setup, receiving end is informed of port)

16 Connection Setup ( SOCK_STREAM )  Recall: no connection setup for SOCK_DGRAM r A connection occurs between two kinds of participants m passive: waits for an active participant to request connection m active: initiates connection request to passive side r Once connection is established, passive and active participants are “similar” m both can send & receive data m either can terminate the connection

17 Connection setup cont’d r Passive participant  step 1: listen (for incoming requests)  step 3: accept (a request) m step 4: data transfer r The accepted connection is on a new socket r The old socket continues to listen for other active participants r Why? r Active participant  step 2: request & establish connect ion m step 4: data transfer Passive Participant l-socka-sock-1a-sock-2 Active 1 socket Active 2 socket

18 Connection setup: listen & accept r Called by passive participant r int status = listen(sock, queuelen);  status : 0 if listening, -1 if error  sock : integer, socket descriptor  queuelen : integer, # of active participants that can “wait” for a connection  listen is non-blocking: returns immediately r int s = accept(sock, &name, &namelen);  s : integer, the new socket (used for data-transfer)  sock : integer, the original socket (being listened on)  name : struct sockaddr, address of the active participant  namelen : sizeof(name): value/result parameter must be set appropriately before call adjusted by OS upon return  accept is blocking: waits for connection before returning

19 connect call r int status = connect(sock, &name, namelen);  status : 0 if successful connect, -1 otherwise  sock : integer, socket to be used in connection  name : struct sockaddr : address of passive participant  namelen : integer, sizeof(name)  connect is blocking

20 Sending / Receiving Data  With a connection ( SOCK_STREAM ): m int count = send(sock, &buf, len, flags); count : # bytes transmitted (-1 if error) buf : char[], buffer to be transmitted len : integer, length of buffer (in bytes) to transmit flags : integer, special options, usually just 0 m int count = recv(sock, &buf, len, flags); count : # bytes received (-1 if error) buf : void[], stores received bytes len : # bytes received flags : integer, special options, usually just 0 m Calls are blocking [returns only after data is sent (to socket buf) / received]

21 Sending / Receiving Data (cont’d)  Without a connection ( SOCK_DGRAM ): m int count = sendto(sock, &buf, len, flags, &addr, addrlen); count, sock, buf, len, flags : same as send addr : struct sockaddr, address of the destination addrlen : sizeof(addr) m int count = recvfrom(sock, &buf, len, flags, &addr, &addrlen); count, sock, buf, len, flags: same as recv name : struct sockaddr, address of the source namelen : sizeof(name): value/result parameter r Calls are blocking [returns only after data is sent (to socket buf) / received]

22 close r When finished using a socket, the socket should be closed: r status = close(s);  status : 0 if successful, -1 if error  s : the file descriptor (socket being closed) r Closing a socket  closes a connection (for SOCK_STREAM ) m frees up the port used by the socket

23 Example: TCP Server program r Make a socket #include int fd, newfd, nbytes, nbytes2; char buf[512], response[512]; struct sockaddr_in srv; fd = socket(AF_INET, SOCK_STREAM, 0);

24 Example: TCP Server program r The socket was created now bind it to a port and host. srv.sin_family = AF_INET; srv.sin_port = htons(80); srv.sin_addr.s_addr = inet_addr(`` ''); /* or srv.sin_addr.s_addr = htonl(IN_ADDR_ANY) bind(fd, (struct sockaddr*) &srv, sizeof(srv)); r Now sit and listen; listen(fd, 5); r Now, accept any connection. First, clear the structure. struct sockaddr_in cli; int cli_len; bzero((char*)&cli, sizeof( cli)); newfd = accept(fd, (struct sockaddr*) &cli, &cli_len); Server address Server port

25 Example: TCP Server program r Now it can read from socket, newfd, and write to socket, newfd. int BUF_ SIZE = 1024, bytesrecv = 0; char buf[ BUF_ SIZE]; /* receives up to BUF_ SIZE bytes from sock and stores them in buf. */ bytesrecv = recv( newfd, buf, BUF_ SIZE, 0); /* send up BUF_ SIZE bytes */ bytesrecv = send( newfd, buf, BUF_ SIZE, 0); r At the end, we need to close both sockets by close command. close( newfd); /* closes the socket newfd */ close( fd); /* closes the socket fd */

26 Example: TCP client program int fd, newfd, nbytes, nbytes2; char buf[512], response[512]; struct sockaddr_in srv; fd = socket(AF_INET, SOCK_STREAM, 0); r The same as server. Now, it needs to connect to server. srv.sin_family = AF_INET; srv.sin_port = htons(80); srv.sin_addr.s_addr = inet_addr(`` ''); /*or srv.sin_addr.s_addr = inet_addr(argv[1]); /*or inet_aton( argv[1], &srv.sin_addr); /*or inet_pton(AF_INET, argv[1], &srv.sin_addr); connect(fd, (struct sockaddr*) &srv, sizeof(srv)); r Connect is blocking and send a SYN signal and is blocked until receive SYNACK, (three way handshaking) r It can start now reading and writing sprintf(request, ``Here's my request''); nbytes2 = write(fd, request, strlen(request)); close(fd); Server address Server port Better than inet_addr

27 Address and port byte-ordering r Address and port are stored as integers m u_short sin_port; (16 bit) m in_addr sin_addr; (32 bit) struct in_addr { u_long s_addr; }; r Problem: m different machines / OS’s use different word orderings little-endian: lower bytes first big-endian: higher bytes first m these machines may communicate with one another over the network Big-Endian machine Little-Endian machine WRONG!!!

28 Solution: Network Byte-Ordering r Defs: m Host Byte-Ordering: the byte ordering used by a host (big or little) m Network Byte-Ordering: the byte ordering used by the network – always big-endian r Any words sent through the network should be converted to Network Byte-Order prior to transmission (and back to Host Byte-Order once received) r Q: should the socket perform the conversion automatically? r Q: Given big-endian machines don’t need conversion routines and little-endian machines do, how do we avoid writing two versions of code?

29 UNIX’s byte-ordering funcs r u_long htonl(u_long x); r u_short htons(u_short x); r u_long ntohl(u_long x); r u_short ntohs(u_short x); r On big-endian machines, these routines do nothing r On little-endian machines, they reverse the byte order r Same code would have worked regardless of endian- ness of the two machines Big-Endian machine Little-Endian machine htonl ntohl

30 Dealing with blocking calls r Many of the functions we saw block until a certain event  accept : until a connection comes in  connect : until the connection is established  recv, recvfrom : until a packet (of data) is received  send, sendto : until data is pushed into socket’s buffer Q: why not until received? r For simple programs, blocking is convenient r What about more complex programs? m multiple connections m simultaneous sends and receives m simultaneously doing non-networking processing

31 Dealing with blocking (cont’d) r Options: m create multi-process or multi-threaded code  turn off the blocking feature (e.g., using the fcntl file- descriptor control function)  use the select function call.  What does select do? m can be permanent blocking, time-limited blocking or non- blocking m input: a set of file-descriptors m output: info on the file-descriptors’ status m i.e., can identify sockets that are “ready for use”: calls involving that socket will return immediately

32 select function call r int status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);  status : # of ready objects, -1 if error  nfds : 1 + largest file descriptor to check  readfds : list of descriptors to check if read-ready  writefds : list of descriptors to check if write-ready  exceptfds : list of descriptors to check if an exception is registered  timeout : time after which select returns, even if nothing ready - can be 0 or  (point timeout parameter to NULL for  )

33 To be used with select :  Recall select uses a structure, struct fd_set m it is just a bit-vector  if bit i is set in [ readfds, writefds, exceptfds ], select will check if file descriptor (i.e. socket) i is ready for [reading, writing, exception]  Before calling select :  FD_ZERO(&fdvar) : clears the structure  FD_SET(i, &fdvar) : to check file desc. i  After calling select :  int FD_ISSET(i, &fdvar) : boolean returns TRUE iff i is “ready”

34 Other useful functions  bzero(char* c, int n): 0’s n bytes starting at c  in_addr_t inet_addr(const char *cp): converts dotted-decimal char-string to long integer  char* inet_ntoa(const struct in_addr in): converts long to dotted-decimal notation  int inet_aton(const char *cp, const struct in_addr in);  gethostname(char *name, int len): gets the name of the current host  gethostbyaddr(char *addr, int len, int type): converts IP hostname to structure containing long integer r Warning: check function assumptions about byte-ordering (host or network). Often, they assume parameters / return solutions in network byte-order

35 Release of ports  Sometimes, a “rough” exit from a program (e.g., ctrl-c ) does not properly free up a port r Eventually (after a few minutes), the port will be freed r To reduce the likelihood of this problem, include the following code: #include void cleanExit(){exit(0);} m in socket code: signal(SIGTERM, cleanExit); signal(SIGINT, cleanExit);