The Socket Interface Chapter 21. Application Program Interface (API) Interface used between...

25
The Socket The Socket Interface Interface Chapter 21 Chapter 21

Transcript of The Socket Interface Chapter 21. Application Program Interface (API) Interface used between...

Page 1: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

The Socket InterfaceThe Socket Interface

Chapter 21Chapter 21

Page 2: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Application Program Interface (API)Application Program Interface (API) Interface used between application programs and Interface used between application programs and

TCP/IP protocolsTCP/IP protocols Will look at one example that is a de facto Will look at one example that is a de facto

standardstandard Things to keep in mindThings to keep in mind

Application/protocol interaction not in the standardsApplication/protocol interaction not in the standards Distinguish between interface and protocolsDistinguish between interface and protocols

In practice, details of interface depend on OS In practice, details of interface depend on OS

Example is from BSD UNIX operating systemExample is from BSD UNIX operating system Is a widely accepted, de facto standardIs a widely accepted, de facto standard Operations listed are NOT part of the TCP/IP standardsOperations listed are NOT part of the TCP/IP standards

Page 3: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

UNIX I/O ParadigmUNIX I/O Paradigm

Unix is a Unix is a processprocess oriented OS oriented OS Applications execute as a user level processApplications execute as a user level process Application interacts with OS via system callsApplication interacts with OS via system calls

Act just like procedure callsAct just like procedure calls

I/O is open-read-write-closeI/O is open-read-write-close Call Call openopen to get file descriptor for file or device to get file descriptor for file or device Call Call readread or or writewrite to do I/O to do I/O Call Call closeclose to indicate done with object to indicate done with object

Page 4: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Adding Network I/O to UNIXAdding Network I/O to UNIX

Originally, all I/O was open-read-write-closeOriginally, all I/O was open-read-write-close

Needed to add network protocols to UNIXNeeded to add network protocols to UNIX Interactions more complexInteractions more complex

Passive server code as well as active client codePassive server code as well as active client code

Specify datagram address when send vs when openSpecify datagram address when send vs when open Abandoned the above paradigmAbandoned the above paradigm Additions made I/O interface more complexAdditions made I/O interface more complex

Needed general mechanism for any protocol interfaceNeeded general mechanism for any protocol interface

Page 5: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Socket AbstractionSocket Abstraction

SocketSocket is basis for network I/O is basis for network I/O Mechanism that provides an endpoint for Mechanism that provides an endpoint for

communicationcommunication Create when needed; get integer to referenceCreate when needed; get integer to reference Application can choose address binding methodApplication can choose address binding method

TCP connectionTCP connection Both endpoints must be specifiedBoth endpoints must be specified

Use for UDPUse for UDP Remote endpoint can be left unspecifiedRemote endpoint can be left unspecified Pass as argument each time message is sentPass as argument each time message is sent

Page 6: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Creating a SocketCreating a Socket

Use Use socketsocket function to create a socket function to create a socket

result = socket(pf, type, protocol)result = socket(pf, type, protocol) pfpf specifies protocol family specifies protocol family typetype specifies communication type specifies communication type

Reliable stream; connectionless datagram; rawReliable stream; connectionless datagram; raw protocolprotocol specifies a specific protocol in the family specifies a specific protocol in the family

Need more than just family and typeNeed more than just family and type

Ex: pipe in UNIX family cannot do packet deliveryEx: pipe in UNIX family cannot do packet delivery

Programmer must know protocol family wellProgrammer must know protocol family well

Page 7: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Socket Inheritance & TerminationSocket Inheritance & Termination

Two system calls used to start new Two system calls used to start new application programsapplication programs forkfork

Creates separate copy of currently executing processCreates separate copy of currently executing process

New copy inherits all open file descriptors & socketsNew copy inherits all open file descriptors & sockets execexec

Desired application program loaded into the processDesired application program loaded into the process

Still retains access to inherited sockets (and FDs)Still retains access to inherited sockets (and FDs)

Page 8: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Page 9: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Page 10: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Page 11: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Page 12: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Both old and new processes share the Both old and new processes share the existing socketsexisting sockets OS keeps a count associated with each socketOS keeps a count associated with each socket

Knows how many applications are using itKnows how many applications are using it Programmer must ensure it is done in a Programmer must ensure it is done in a

meaningful waymeaningful way

To close a socket:To close a socket:close(socket)close(socket)

Or, open sockets closed upon process terminationOr, open sockets closed upon process termination closeclose actually decrements count; destroy socket actually decrements count; destroy socket

when it reaches zerowhen it reaches zero

Page 13: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Specifying a Specifying a LocalLocal Address Address

Upon creation, sockets have no association Upon creation, sockets have no association to local or destination addressesto local or destination addresses TCP/IPTCP/IP

No local protocol port number has been assignedNo local protocol port number has been assigned

No destination port or IP address has been specifiedNo destination port or IP address has been specified Client may not care what local address isClient may not care what local address is

Server process at well-know port Server process at well-know port willwill care care

Uses Uses bindbind function to establish specific local addrs function to establish specific local addrs

Page 14: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Connecting Sockets to Connecting Sockets to DestinationDestination AddressesAddresses

Initially, sockets are Initially, sockets are unconnectedunconnected Not associated with any remote destinationNot associated with any remote destination Function Function connectconnect binds a permanent destination binds a permanent destination Form:Form:

connect(socket, destaddr, addrlen)connect(socket, destaddr, addrlen) Semantics depend upon underlying protocolSemantics depend upon underlying protocol

Reliable stream service: build TCP connectionReliable stream service: build TCP connection

Connectionless service: stores dest address locallyConnectionless service: stores dest address locally

Page 15: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Sending Data Through a SocketSending Data Through a Socket

Sockets are used to transmit dataSockets are used to transmit data Five possible functionsFive possible functions

writewrite write(socket, buffer, length)write(socket, buffer, length) bufferbuffer contains the address of the data to be sent contains the address of the data to be sent Works with connected sockets onlyWorks with connected sockets only

writevwritev writev(socket, iovector, vectorlen)writev(socket, iovector, vectorlen) iovectoriovector contains a sequence of pointers to blocks of bytes contains a sequence of pointers to blocks of bytes Works with connected sockets onlyWorks with connected sockets only

Page 16: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

sendsend send(socket, message, length, flags)send(socket, message, length, flags) messagemessage gives the address of the data gives the address of the data flagsflags controls the transmission controls the transmission Works with connected sockets onlyWorks with connected sockets only

sendtosendto sendto(socket, message, length, flags, destaddr, sendto(socket, message, length, flags, destaddr,

addrlen)addrlen) destaddrdestaddr specifies the socket address structure specifies the socket address structure

sendmsgsendmsg sendmsg(socket, messagestruct, flags)sendmsg(socket, messagestruct, flags) messagestructmessagestruct is a structure with the required is a structure with the required

informationinformation Used when Used when sendtosendto makes the program inefficient or makes the program inefficient or

hard to readhard to read

Page 17: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Receiving Data Through a Receiving Data Through a SocketSocket

Analogous five input functionsAnalogous five input functions readread(descriptor, buffer, length)(descriptor, buffer, length) readvreadv(descriptor, iovector, vectorlen)(descriptor, iovector, vectorlen) recvrecv(socket, buffer, length, flags)(socket, buffer, length, flags) recfromrecfrom(socket, buffer, length, flags, fromaddr, (socket, buffer, length, flags, fromaddr,

addrlen)addrlen) recmsgrecmsg(socket, messagestruct, flags)(socket, messagestruct, flags)

Page 18: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Text gives examples of many socket Text gives examples of many socket functions and library routinesfunctions and library routines Can read over at your convenienceCan read over at your convenience

Page 19: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

How a Server Accepts ConnectionsHow a Server Accepts Connections

Once a socket is established, the server Once a socket is established, the server waits for a connectionwaits for a connection Uses function Uses function acceptaccept to do so to do so

newsock = accept(socket, addr, addrlen)newsock = accept(socket, addr, addrlen)

When a request arrives:When a request arrives: addraddr and and addrlenaddrlen filled in filled in New socket created that has destination connected to clientNew socket created that has destination connected to client Original socket still remains openOriginal socket still remains open Call to Call to acceptaccept returns returns

Page 20: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Server can handle connections one of two waysServer can handle connections one of two waysIterativelyIteratively

Server handles request, closes new socket, calls Server handles request, closes new socket, calls acceptaccept

ConcurrentlyConcurrently Master creates slave to handle request at new socketMaster creates slave to handle request at new socket

Closes its copy of the new socketCloses its copy of the new socket

Calls Calls acceptaccept Slave closes socket when it finishes, and then terminatesSlave closes socket when it finishes, and then terminates Multiple processes will be using same local protocol portMultiple processes will be using same local protocol port

Ok because pair of endpoints defines a connectionOk because pair of endpoints defines a connection

Master server has wildcard in foreign destinationMaster server has wildcard in foreign destination

All other processes have a specific foreign destAll other processes have a specific foreign dest

Page 21: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Socket Library CallsSocket Library CallsSocket API also offers set of library routinesSocket API also offers set of library routines Perform useful functions related to networkingPerform useful functions related to networking

System calls pass control to computer’s OSSystem calls pass control to computer’s OS

Library routines are like other program proceduresLibrary routines are like other program procedures

Figure 21.5Figure 21.5

Page 22: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Many socket library routines provide database Many socket library routines provide database servicesservices

Determine names of machines & network servicesDetermine names of machines & network services

Determine protocol port numbersDetermine protocol port numbers

Find out other related informationFind out other related information Sections 21.19 - 21.25 examine groups of Sections 21.19 - 21.25 examine groups of

library routineslibrary routines

Page 23: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

Example Client & ServerExample Client & Server

Text gives example C program using the Text gives example C program using the socket API to access TCP/IP protocolssocket API to access TCP/IP protocols Implements simple Implements simple whoiswhois client & server client & server Client is an application that a user invokesClient is an application that a user invokes

Two arguments: name of remote machine and userTwo arguments: name of remote machine and userCreates socket, uses TCP, binds socket to Creates socket, uses TCP, binds socket to whois whois portport

Server only slightly more complexServer only slightly more complexListens on well-know Listens on well-know whoiswhois port portReturns requested info from UNIX password fileReturns requested info from UNIX password file

Page 24: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

SummarySummary

API for TCP/IP depends on details of OSAPI for TCP/IP depends on details of OS Because TCP/IP protocol SW resides inside OSBecause TCP/IP protocol SW resides inside OS Interface not specified by protocol standardInterface not specified by protocol standard

Examined socket APIExamined socket API Originally designed for BSD UNIXOriginally designed for BSD UNIX Widely used by many vendors (like Microsoft)Widely used by many vendors (like Microsoft) Uses UNIX open-read-write-close paradigmUses UNIX open-read-write-close paradigm

Page 25: The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.

To use TCP, application program must:To use TCP, application program must:

Create socketCreate socket

Bind addresses to itBind addresses to it

Accept incoming connectionsAccept incoming connections

Communicate using read or write primitivesCommunicate using read or write primitives

Close when finishedClose when finished Many library routines available, alsoMany library routines available, also Socket interface is popular and widely supportedSocket interface is popular and widely supported

If not have socket facilities in OS, often provide socket If not have socket facilities in OS, often provide socket librarylibrary

Underlying OS will use different set of system callsUnderlying OS will use different set of system calls