TCPIPPowerPoint演示文稿

上传人:ni****g 文档编号:589882508 上传时间:2024-09-11 格式:PPT 页数:89 大小:204.50KB
返回 下载 相关 举报
TCPIPPowerPoint演示文稿_第1页
第1页 / 共89页
TCPIPPowerPoint演示文稿_第2页
第2页 / 共89页
TCPIPPowerPoint演示文稿_第3页
第3页 / 共89页
TCPIPPowerPoint演示文稿_第4页
第4页 / 共89页
TCPIPPowerPoint演示文稿_第5页
第5页 / 共89页
点击查看更多>>
资源描述

《TCPIPPowerPoint演示文稿》由会员分享,可在线阅读,更多相关《TCPIPPowerPoint演示文稿(89页珍藏版)》请在金锄头文库上搜索。

1、TCP/IP Part IIBased on Notes by D. HollingerBased on Notes by D. HollingerBased on UNIX Network Programming, Stevens, Based on UNIX Network Programming, Stevens, Chapters 7,11,21,22,27Chapters 7,11,21,22,27Also Java Network Programming and Also Java Network Programming and Distributed Computing, Cha

2、pter 6Distributed Computing, Chapter 6Also Online Java Tutorial, Sun.Also Online Java Tutorial, Sun.1Topicsl lIssues in Client/Server Programmingl lAdvanced TCP/IP Optionsl lSample Application-layer ProtocolsTELNETTELNETFTPFTP2Issues in Client Programmingl lIdentifying the Server.l lLooking up an IP

3、 address.l lLooking up a well known port name.l lSpecifying a local IP address.l lUDP client design.l lTCP client design.3Identifying the Serverl lOptions:hard-coded into the client program.hard-coded into the client program.require that the user identify the server.require that the user identify th

4、e server.read from a configuration file.read from a configuration file.use a separate protocol/network service to use a separate protocol/network service to lookup the identity of the server. lookup the identity of the server. 4Identifying a TCP/IP server.l lNeed an IP address, protocol and port.We

5、often use We often use host nameshost names instead of IP instead of IP addresses.addresses.usually the protocol (UDP vs. TCP) is not usually the protocol (UDP vs. TCP) is not specified by the user.specified by the user.often the port is not specified by the user.often the port is not specified by t

6、he user.Can you name one common exception ?Can you name one common exception ?5Services and Portsl lMany services are available via “well known” addresses (names).l lThere is a mapping of service names to port numbers.6Specifying a Local Addressl lWhen a client creates and binds a socket it must spe

7、cify a local port and IP address.l lTypically a client doesnt care what port it is on:mySocket = new DatagramSocket()mySocket = new DatagramSocket()give me any available port !give me any available port !7Local IP addressl lA client can also ask the operating system to take care of specifying the lo

8、cal IP address:myAddress = myAddress = InetAddress.getLocalHost();InetAddress.getLocalHost();Give me the appropriate addressGive me the appropriate address8UDP Client Designl lEstablish server address (IP and port).l lAllocate a socket.l lSpecify that any valid local port and IP address can be used.

9、l lCommunicate with server (send, receive)l lClose the socket.9Connected mode UDPl lA UDP client can call connect(address, port) to establish the address of the server.l l“connect” is a misnomer:A UDP client using a connected mode A UDP client using a connected mode socket can only talk to that serv

10、er (using socket can only talk to that server (using the connected-mode socket).the connected-mode socket).10TCP Client Designl lEstablish server address (IP and port).l lAllocate a socket.l lSpecify that any valid local port and IP address can be used. l lCall connect()l lCommunicate with server (t

11、hrough given streams).l lClose the connection.Transparent to Java programmers11Closing a TCP socketl lMany TCP based application protocols support multiple requests and/or variable length requests over a single TCP connection.l l How does the server known when the client is done (and it is OK to clo

12、se the socket) ?12Partial Closel lOne solution is for the client to shut down One solution is for the client to shut down only its writing end of the socket.only its writing end of the socket.l lThe The shutdownOutput()shutdownOutput() socket call socket call provides this function.provides this fun

13、ction. mySocket.shutdownOutput();mySocket.shutdownOutput(); shutdownOutput() flushes output stream and shutdownOutput() flushes output stream and sends TCP-connection termination sequence.sends TCP-connection termination sequence. shutdownInput() closes input stream and discards shutdownInput() clos

14、es input stream and discards any further information (further read()s will get -1)any further information (further read()s will get -1)13TCP sockets programmingl lCommon problem areas:null termination of strings. null termination of strings. reads dont correspond to writes.reads dont correspond to w

15、rites.synchronization (including close().synchronization (including close().ambiguous protocol.ambiguous protocol.Not a problem with Java Strings.14TCP Readsl lEach call to read() on a TCP socket returns any available data (up to a maximum).l lTCP buffers data at both ends of the connection. l lYou

16、must be prepared to accept data 1 byte at a time from a TCP socket.15Server DesignIterativeConnectionlessIterativeConnection-OrientedConcurrentConnection-OrientedConcurrentConnectionless16Concurrent vs. IterativeIterativeSmall, fixed size requestsEasy to programConcurrentLarge or variable size reque

17、stsHarder to programTypically uses more system resources17Connectionless vs.Connection-OrientedConnection-OrientedEASY TO PROGRAMtransport protocol handles the tough stuff.requires separate socket for each connection.Connectionlessless overheadno limitation on number of clients18Statelessnessl lStat

18、e: Information that a server maintains about the status of ongoing client interactions.l lConnectionless servers that keep state information must be designed carefully!Messages can be duplicated!Messages can be duplicated!19The Dangers of Statefullnessl lClients can go down at any time.l lClient hos

19、ts can reboot many times.l lThe network can lose messages.l lThe network can duplicate messages.20Concurrent ServerDesign AlternativesOne process per clientSpawn one thread per clientPreforking multiple processesPrethreaded Server21One child process per clientl lTraditional Unix server:Traditional U

20、nix server: TCP: after call to TCP: after call to accept(),accept(), call call getRuntime().exec(), returns Process.getRuntime().exec(), returns Process. UDP: after UDP: after receive(),receive(), call call exec().exec(). Each process needs only a few sockets.Each process needs only a few sockets. S

21、mall requests can be serviced in a small amount of Small requests can be serviced in a small amount of time.time.l lParent process needs to clean up after Parent process needs to clean up after children! (invoke children! (invoke waitFor()waitFor() ). ).22One thread per clientl lUse new Thread().sta

22、rt();l lUsing threads makes it easier (less overhead) to have sibling processes share information.l lSharing information must be done carefully (use synchronized)Watch out for deadlocks!23Pre-forked Serverl lCreating a new process for each client is expensive.l lWe can create a bunch of processes, e

23、ach of which can take care of a client.l lEach child process is an iterative server.24Pre-forked TCP Serverl lInitial process creates socket and binds to well known address. l lProcess now calls exec() a bunch of times.l lAll children call accept().l lThe next incoming connection will be handed to o

24、ne child.25Sockets library vs. system calll lA pre-forked TCP server wont usually work the way we want if sockets is not part of the kernel:calling accept() is a library call, not an calling accept() is a library call, not an atomic operation.atomic operation.l lWe can get around this by making sure

25、 only one child calls accept() at a time using some locking scheme.26Pre-forkingl lHaving too many pre-forked children can be bad.l lUsing dynamic process allocation instead of a hard-coded number of children can avoid problems.l lThe parent process just manages the children, doesnt worry about clie

26、nts.27Pre-threaded Serverl lSame benefits as pre-forking.l lCan have the main thread do all the calls to accept() and hand off each client to an existing thread.28Whats the best server design for my application?l lMany factors:Expected number of simultaneous clients.Expected number of simultaneous c

27、lients.Transaction size (time to compute or Transaction size (time to compute or lookup the answer)lookup the answer)Variability in transaction size.Variability in transaction size.Available system resources (perhaps what Available system resources (perhaps what resources can be required in order to

28、 run resources can be required in order to run the service).the service).29Server Designl lIt is important to understand the issues and options.l lKnowledge of queuing theory can be a big help.l lYou might need to test a few alternatives to determine the best design.30l lIts important to know about

29、some of these topics, although it might not be apparent how and when to use them.l lDetails are in the book(s) - we are just trying to get some idea of what can be done.TCP Socket Options31Socket Optionsl lVarious attributes that are used to determine the behavior of sockets.l lSetting options tells

30、 the OS/Protocol Stack the behavior we want.l lSupport for generic options (apply to all sockets) and protocol specific options.32Option typesl lMany socket options are boolean flags indicating whether some feature is enabled (true) or disabled (false).l lOther options are associated with different

31、data types, e.g. int, representing time.33Read-Only Socket Optionsl lSome options are readable only (we cant set the value).34Setting and Getting option valuesgetOption()getOption() gets the current value of a gets the current value of a socket option, e.g.socket option, e.g.getReceiveBufferSize();g

32、etReceiveBufferSize();setOption()setOption() is used to set the value of a is used to set the value of a socket option, e.g.socket option, e.g.setReceiveBufferSize(size);setReceiveBufferSize(size);35Some Generic OptionsSO_BROADCASTSO_DONTROUTESO_ERRORSO_KEEPALIVESO_LINGERSO_RCVBUF,SO_SNDBUFSO_REUSEA

33、DDR36SO_BROADCASTl lBoolean option: enables/disables sending of broadcast messages.l lUnderlying DL layer must support broadcasting!l lApplies only to Datagram (UDP) sockets.l lPrevents applications from inadvertently sending broadcasts (OS looks for this flag when broadcast address is specified).37

34、SO_DONTROUTEl lBoolean option: enables bypassing of normal routing.l lUsed by routing daemons.38SO_ERRORl lInteger value option. l lThe value is an error indicator value (similar to errno).l lReadable (getable) only!l lIn Java, a SocketException, or IOException is thrown.39SO_KEEPALIVEl lBoolean opt

35、ion: enabled means that STREAM sockets should send a probe to peer if no data flow for a “long time”.l lUsed by TCP - allows a process to determine whether peer process/host has crashed. l lConsider what would happen to an open telnet connection without keepalive.40SO_LINGERl lUsed to control whethe

36、r and how long a call to close will wait for pending ACKS. l lconnection-oriented sockets only. l lsetSoLinger(boolean onFlag, int duration);l lgetSoLinger(); returns duration (-1 if option is disabled)41SO_LINGER usagel lBy default, calling close() on a TCP socket will return immediately.l lThe clo

37、sing process has no way of knowing whether or not the peer received all data.l lSetting SO_LINGER means the closing process can determine that the peer machine has received the data (but not that the data has been read() !).42shutdown() vs SO_LINGERl lYou can use shutdownIn|Output() to find out when

38、 the peer process has read all the sent data.43SO_RCVBUFSO_SNDBUFl lInteger values options - change the receive Integer values options - change the receive and send buffer sizes.and send buffer sizes.l lCan be used with TCP and UDP sockets.Can be used with TCP and UDP sockets.l lWith TCP, this optio

39、n effects the window size With TCP, this option effects the window size used for flow control - must be established used for flow control - must be established before connection is made.before connection is made. g|setSend|ReceiveBufferSize();g|setSend|ReceiveBufferSize();44SO_REUSEADDRl lBoolean op

40、tion: enables binding to an address (port) that is already in use.l lUsed by servers that are transient - allows binding a passive socket to a port currently in use (with active sockets) by other processes.45SO_REUSEADDRl lCan be used to establish separate servers for the same service on different i

41、nterfaces (or different IP addresses on the same interface).l lVirtual Web Servers can work this way.46SO_TIMEOUTl lCan be used to tell the socket to use non-blocking read.l lgetSoTimeout() returns the current setting (by default 0, or disabled, representing a blocking read).l lE.g. to tell socket t

42、o interrupt reading if 5 seconds pass by, use:mySocket.setSoTimeout(5000);mySocket.setSoTimeout(5000);47IP Options (IPv4)l lIP_TOS: allows us to set the “Type-of-service” field in an IP header.setTrafficClass(int);setTrafficClass(int);48another TCP socket optionl lTCP_NODELAY: can disable TCPs Nagle

43、 TCP_NODELAY: can disable TCPs Nagle algorithm that delays sending small packets if algorithm that delays sending small packets if there is unACKd data pending.there is unACKd data pending.l lTCP_NODELAY also disables delayed ACKS TCP_NODELAY also disables delayed ACKS (TCP ACKs are cumulative).(TCP

44、 ACKs are cumulative).l lJava Sockets:Java Sockets: getTcpNoDelay();getTcpNoDelay(); setTcpNoDelay(flag);setTcpNoDelay(flag);49Out-of-Band Datel lEver been on a date, gone to a dance club and the band doesnt show up?This is becoming a serious problem: This is becoming a serious problem: uuThe number

45、 of Internet dating services is The number of Internet dating services is growing exponentially.growing exponentially.uuThe number of bands is not growing.The number of bands is not growing.RFC 90210 proposes some short term RFC 90210 proposes some short term solutions (until the number of bands can

46、 be solutions (until the number of bands can be increased).increased).50Out-of-Band Datal lTCP (and other transport layers) provide a mechanism for delivery of high priority data ahead of normal data.l lWe can almost think of this as 2 streams:TCP PORTATCP PORTBnormal dataspecial data51TCP OOB Datal

47、 lTCP supports something like OOB data using URGENT MODE (a bit is set in a TCP segment header). l lA TCP segment header field contains an indication of the location of the urgent data in the stream (the byte number).52Sending OOB DatasendUrgentData(int data);Puts a single byte of urgent data in a T

48、CP stream (lowest 8 bits).The TCP layer adds some segment header info to let the other end know there is some OOB data.53Receiving OOB Datal lReceiver needs to set OOBInline flag:setOOBInline(true);setOOBInline(true);l lUrgent data is inlined with normal data.l lVery limited support in Java.No speci

49、al notification of urgent data, and No special notification of urgent data, and no distinction between normal and urgent no distinction between normal and urgent data, unless provided by higher-level data, unless provided by higher-level protocol.protocol.54l lThis was just an overviewthere are many

50、 details associated with the there are many details associated with the options described.options described.There are many options that havent been There are many options that havent been described.described.UNIX Network Programming is one of the UNIX Network Programming is one of the best sources o

51、f information about socket best sources of information about socket options. options. Socket Options SummaryNot ALL options are (fully) supported by Java.55The TELNET ProtocolReference: RFC 85456TELNET vs. telnetl lTELNET is a protocol that provides “a general, bi-directional, eight-bit byte oriente

52、d communications facility”.l ltelnet is a program that supports the TELNET protocol over TCP.l lMany application protocols are built upon the TELNET protocol.57The TELNET Protocoll lTCP connectionl ldata and control over the same connection.l lNetwork Virtual Terminall lnegotiated options58Network V

53、irtual Terminall lintermediate representation of a generic terminal.l lprovides a standard language for communication of terminal control functions.59Network Virtual TerminalNVTNVTNVTNVTServerProcessTCPTCPTCPTCP60Negotiated Optionsl lAll NVTs support a minimal set of capabilities.l lSome terminals h

54、ave more capabilities than the minimal set.l lThe 2 endpoints negotiate a set of mutually acceptable options (character set, echo mode, etc).61Negotiated Optionsl lThe protocol for requesting optional features is well defined and includes rules for eliminating possible negotiation “loops”.l lThe set

55、 of options is not part of the TELNET protocol, so that new terminal features can be incorporated without changing the TELNET protocol.62Option examplesl lLine mode vs. character model lecho modesl lcharacter set (EBCDIC vs. ASCII)63Control Functionsl lTELNET includes support for a series of control

56、 functions commonly supported by servers.l lThis provides a uniform mechanism for communication of (the supported) control functions.64Control Functionsl lInterrupt Process (IP)suspend/abort process.suspend/abort process.l lAbort Output (AO)process can complete, but send no more process can complete

57、, but send no more output to users terminal.output to users terminal.l lAre You There (AYT)check to see if system is still running.check to see if system is still running.65More Control Functionsl lErase Character (EC)delete last character sentdelete last character senttypically used to edit keyboar

58、d input.typically used to edit keyboard input.l lErase Line (EL)delete all input in current line.delete all input in current line.66Command Structurel lAll TELNET commands and data flow through the same TCP connection.l lCommands start with a special character called the Interpret as Command escape

59、character (IAC).l lThe IAC code is 255.l lIf a 255 is sent as data - it must be followed by another 255.67Looking for Commandsl lEach receiver must look at each byte that arrives and look for IAC.l lIf IAC is found and the next byte is IAC - a single byte is presented to the application/terminal (a

60、255).l lIf IAC is followed by any other code - the TELNET layer interprets this as a command.68Command Codesl lIP243l lAO 244l lAYT245l lEC246l lEL247n nWILL251n nWONT 252n nDO253n nDONT 254n nIAC25569Playing with TELNETl lYou can use the telnet program to play with the TELNET protocol.l ltelnet is

61、a generic TCP client.Sends whatever you type to the TCP Sends whatever you type to the TCP socket.socket.Prints whatever comes back through the Prints whatever comes back through the TCP socket.TCP socket.Useful for testing TCP servers (ASCII Useful for testing TCP servers (ASCII based protocols).ba

62、sed protocols).70Some TCP Servers you can play withl lMany Unix systems have these servers running (by default):echoechoport 7port 7discarddiscardport 9port 9daytimedaytimeport 13port 13chargenchargenport 19port 1971telnet hostname port telnet rcs.rpi.edu 7telnet rcs.rpi.edu 7Trying 128.113.113.33.T

63、rying 128.113.113.33.Connected to cortez.sss.rpi.edu Connected to cortez.sss.rpi.edu (128.113.113.33).(128.113.113.33).Escape character is .Escape character is .Hi daveHi daveHi daveHi davestop itstop itstop itstop ittelnet telnet quitquitConnection closed.Connection closed.72telnet vs. TCPl lNot al

64、l TCP servers talk TELNET (most dont) l lYou can use the telnettelnet program to play with these servers, but the fancy commands wont do anything.type , then help for a list of fancy TELNET stuff type , then help for a list of fancy TELNET stuff you can do in you can do in telnettelnet. .73FTPFile T

65、ransfer ProtocolReference:RFC 95974FTP Objectives(from RFC 959)promote sharing of filesencourage indirect use of remote computersshield user from variations in file storagetransfer data reliably and efficiently“FTP, although usable directly by a user at a terminal, is designed mainly for use by prog

66、rams”75The FTP ModelServer PIServer PIFileFileSystemSystemUser InterfaceUser InterfaceUser PIUser PIUserUserUser DTPUser DTPServer DTPServer DTPFileFileSystemSystemDataDataControlControlPI: Protocol InterpreterPI: Protocol InterpreterDTP: Data Transfer ProtocolDTP: Data Transfer Protocol76Control an

67、d Data ConnectionsControl functions (commands) and reply codes are transferred over the control connection.All data transfer takes place over the data connection.The control connection must be “up” while data transfer takes place.77Control ConnectionThe control connection is the “well known” service

68、.The control connection uses the TELNET protocol.Commands and replies are all line oriented text (default is ASCII).78Standard Connection Model ControlDataAB79Alternative Connection ModelControlDataABCControl80Access Control CommandsUSER specify user PASS specify passwordCWD change directoryCDUPchan

69、ge directory to parentQUITlogout81Transfer Parameter CommandsPORT publish local data portPASVserver should listen TYPEestablish data representationMODEestablish transfer modeSTRUestablish file structure82Service CommandsRETRretrieve fileSTORsend fileSTOUsend file and save as uniqueAPPEsend file and

70、append ABORabort prev. service commandPWDprint working directoryLISTtransfer list of files over data link83FTP RepliesAll replies are sent over control connection.Replies are a single line containing3 digit status code (sent as 3 numeric 3 digit status code (sent as 3 numeric chars).chars).text mess

71、age.text message.The FTP spec. includes support for multiline text replies.84FTP Reply Status CodeFirst digit of status code indicates type of reply:1: Positive Preliminary Reply (got it, but wait).1: Positive Preliminary Reply (got it, but wait).2: Positive Completion Reply (success).2: Positive Co

72、mpletion Reply (success).3: Positive Intermediate Reply (waiting for more 3: Positive Intermediate Reply (waiting for more information).information).4: Transient Negative Completion (error - try 4: Transient Negative Completion (error - try again).again).5: Permanent Negative Reply (error - cant do)

73、.5: Permanent Negative Reply (error - cant do).85FTP Reply Status Code2nd digit indicates function groupings.2nd digit indicates function groupings.0: Syntax (problem with command syntax).0: Syntax (problem with command syntax).1: Information (reply to help or status1: Information (reply to help or

74、status cmds cmds). ).2: Connections (problem with a connection).2: Connections (problem with a connection).3: Authentication (problem with login).3: Authentication (problem with login).4: Unspecified.4: Unspecified.5: File system (related to file system).5: File system (related to file system).3rd d

75、igit indicates specific problem within 3rd digit indicates specific problem within function group. function group. 86Data Transfer ModesSTREAM: file is transmitted as a stream of STREAM: file is transmitted as a stream of bytes.bytes.BLOCK: file is transmitted as a series of BLOCK: file is transmitt

76、ed as a series of blocks preceded by headers containing count blocks preceded by headers containing count and descriptor code (EOF, EOR, restart and descriptor code (EOF, EOR, restart marker).marker).COMPRESSED: uses a simple compression COMPRESSED: uses a simple compression scheme - compressed bloc

77、ks are transmitted. scheme - compressed blocks are transmitted. 87RFC 959The RFC includes lots more information and many details including:parameters for commandsparameters for commandslists of reply status codeslists of reply status codesprotocol state diagramsprotocol state diagramssupport for a variety of file structuressupport for a variety of file structuressample sessionssample sessions88若有不当之处,请指正,谢谢!89

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 医学/心理学 > 基础医学

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号