Skip this Video
Download Presentation
Chapter III

Loading in 2 Seconds...

play fullscreen
1 / 35

Chapter III - PowerPoint PPT Presentation

  • Uploaded on

Chapter III. TCP. workhorse of the Internet – 1974 - data stream (mule train versus conveyor belt) most traffic suited to TCP: - long conversations like SSH, large exchanges like HTTP Reliability : packet sequence numbers and retransmission.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Chapter III' - amal

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Chapter III

  • workhorse of the Internet – 1974

- data stream (mule train versus conveyor belt)

  • most traffic suited to TCP:

- long conversations like SSH, large exchanges like HTTP

  • Reliability: packet sequence numbers and retransmission.
  • TCP Sequence Number: byte number of first byte in data package plus 1 for SYN and 1 for FIN
  • Retransmitted packets can begin at different packet boundaries.
  • Initial SeqNum is randomly choosen to confound “villains”.
tcp is bursty
net_pyTCP is bursty
  • TCP noes not keep the sender and receiver in lock-step.
  • Sender can send multiple packets with no acknowledgment of any being received.
tcp example

byte 10, len 10

byte 20, len 10

byte 30, len 10

byte 15, len 20

byte 40, len 10

TCP Example



next expected

byte number is


ACK 15


ACK 40

tcp window

byte 10, len 10

byte 20, len 10

byte 30, len 10

byte 15, len 20

byte 40, len 10

TCP Window



TCP Window:

Sender has sent 40

bytes with no ACK

received. So its

window is 40 bytes.

Actual Window size:


ACK 15


ACK 40

tcp overwhelmed

byte 10, len 10

byte 20, len 10

byte 30, len 10

byte 15, len 20

byte 40, len 10

TCP Overwhelmed



TCP Overwhelmed:

Receiver, if over-

whelmed, sends TCP

option, telling sender

to shut window down;

specifies window new

window size.

ACK 15


ACK 40

tcp congested

byte 10, len 10

byte 20, len 10

byte 30, len 10

byte 15, len 20

byte 40, len 10

TCP Congested



TCP Congested:

Receiver, if it sees a

missing packet,

assumes congestion

and shuts the window

down as in the case of

being overwhelmed.

ACK 15


ACK 40

when to use tcp
net_pyWhen to use TCP
  • Most of the time.
  • When is it inappropriate?

- single request/reply exchange – TCP uses 9 packets in total

- too many clients – each connection costs memory allocation, port allocation, etc.

- real time like audio chat; retransmitted voice is discarded because conversation has moved on.

normally compressed voice

highly compressed voice from previous and next packet

tcp socket
net_pyTCP Socket
  • Listen Sockets and Data Sockets.
  • Listen Sockets: like UDP, open and waiting for SYN
  • Data Sockets always involve a connection.
  • UDP socket.connect() shows intention of data exchange between two particular processes and is optional
  • TCP socket.connect() does the same and is fundamental.

(localIP,localport,remoteIP, remoteport)





data. ACK


passive socket



in a loop

listen = socket.listen()

only accepts SYN

s_data = listen.accept()

and blocks

c_data = socket.connect()



active sockets,

c_data and s_data are

identical in nature, identified by


ie a connection

NOTE: Hundreds or thousands of active sockets are possible on server with

same (srvIP,srvPort) pair but only one passive socket with the same pair.


#!/usr/bin/env python

# Foundations of Python Network Programming - Chapter 3 -

# Simple TCP client and server that send and receive 16 octets

import socket, sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# doesn't know yet if active or passive

HOST = sys.argv.pop() if len(sys.argv) == 3 else ''

PORT = 1060

def recvall(sock, length): # used by both client and server

data = ''

while len(data) < length: # building a complete message

more = sock.recv(length - len(data))

if not more:

raise EOFError('socket closed %d bytes into a %d-byte message'

% (len(data), length))

data += more

return data


if sys.argv[1:] == ['server']:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((HOST, PORT)) # bind to whatever we wish


while True:

print 'Listening at', s.getsockname()

sc, sockname = s.accept()

print 'We have accepted a connection from', sockname

print 'Socket connects', sc.getsockname(), 'and', sc.getpeername()

message = recvall(sc, 16)

print 'The incoming sixteen-octet message says', repr(message)

sc.sendall('Farewell, client')


print 'Reply sent, socket closed'

socket so reuseaddr


1: When a server passive socket is closed, TCP does not allow it to be

reused for several minutes to give all clients a chance to see that any future

listener is a new listener. If you want to rerun the program multiple times (as

in testing) then allow immediate reuse of the same passive socket.

2: If a popular server goes down you would want it to come back up immediately

and so for the same reason we set the SO_REUSEADDR socket option.


elif sys.argv[1:] == ['client']:

s.connect((HOST, PORT)) # can fail; unlike UDP

print 'Client has been assigned socket name', s.getsockname()

s.sendall('Hi there, server')

reply = recvall(s, 16)

print 'The server said', repr(reply)



print >>sys.stderr, 'usage: server|client [host]'

NOTE: Calling send(), TCP might not send all bytes immediately and

returns the number actually sent;

calling sendall() asks that all data be sent asap and that happens before

the function call returns. Notice that program does not capture sendall()

return value.

NOTE: recv_all() loops until all expected data is received.


  • Create two sockets, one UPD and the other TCP and call connect on both of them to a non-existent remote socket. See what happens

[[email protected] 03]$ python

Python 2.7.3 (default, Jul 24 2012, 10:05:38)

>>> import socket

>>> udp_s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

>>> tcp_s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

>>> udp_s.connect(('',1060))

# [[email protected] 03]$ netstat -an | grep 215


>>> tcp_s.connect(('',1060))

Traceback (most recent call last):

File "", line 1, in

File "/usr/lib64/python2.7/", line 224, in meth

return getattr(self._sock,name)(*args)

socket.error: [Errno 110] Connection timed out


tcp send
net_pyTCP send()
  • The Stack has space so send() dumps all its data into a TCP buffer and returns, even though nothing has been sent. From now on, it is TCP's headache.
  • TCP buffer is full or Stack is busy so send() blocks
  • TCP buffer has some space but not enough for all send() wants to transmit so send() moves as much data as it can into the TCP buffer and returns that number. It is the program's responsibility to recall send() with data starting at the first byte not previously accepted by TCP.
tcp send code
net_pyTCP send() code:

bytes_sent = 0

while bytes_sent < len(message):

message_remaining = message[bytes_sent:]

bytes_sent += s.send(message_remaining)

# python has a sendall() function that does this for us.

tcp recv
net_pyTCP recv()
  • Works like send():
  • If no data then recv() blocks
  • if plenty available then gives back just what the call asks for
  • if some data available but not what you ask for you are gien what is available and need to build up your own complete message by repeatedly calling recv().
no tcp recvall
net_pyNo TCP recvall()?
  • Because we hardly ever know in advance the precise size we are expecting. For example, suppose we send out an HTTP GET request to
  • The data that comes back consists of a header, a blank line and some data.
  • The header may or may not contain a Content-Length field.
  • If it does we know exactly how many bytes to read so could use a recvall() function. If not then we just need to read until we feel we've come to the end of the data.
  • In Listing 1.5 this means until we come to the end of a syntactically correct JSON data object, serialized.

HTTP/1.1 200 OK

Content-Type: text/javascript; charset=UTF-8

Vary: Accept-Language

Date: Wed, 21 Jul 2010 16:10:38 GMT

Server: mafe

Cache-Control: private, x-gzip-ok=""

X-XSS-Protection: 1; mode=block

Content-Length: 481

Connection: close


"name": "207 N. Defiance St, Archbold, OH",

"Status": {

"code": 200,

"request": "geocode"


"Placemark": [ {


"Point": {

"coordinates": [ -84.3063479, 41.5228242, 0 ]


} ]


tcp segment
net_pyTCP Segment

Options fields possible

tcp sliding window
net_pyTCP sliding window
  • Sliding-window protocol without selective or negative acknowledgment.
  • window “belongs” to sender; each end of a connection has a window
  • n1: byte (sequence) number of next byte to be transmitted for the first time
  • n2: byte (sequence) number of next byte to be acknowledged
  • B: data already transmitted but not acknowledged
  • A, C?

data stream to be transmitted








window direction

direction of data flow

tcp acknowledgment
net_pyTCP Acknowledgment:
  • TCP does not “negative” acknowledge; ie, send a message that something is missing
  • TCP does not “selectively” acknowledge; ie, send a message that a specific byte range has been received
  • TCP acknowledgment number means TCP has received all bytes up to but not including the ACK number.
tcp flow control
net_pyTCP Flow Control
  • TCP sends a window size field in its header. This field is used by the end that receives the TCP segment to control its own sliding window size.
  • Typical window size is 4096. If the receiver end of a connection sends a TCP header with a smaller number the sender slows down transmission of new bytes until more bytes are acknowledged by the other end (hence n1 – n2 shrinks)
tcp options
net_pyTCP Options
  • MSS: Maximum Segment Size. Usually sent during 3-way handshake so that both ends will know how big (or small) future segments should be.
tcp timeout
net_pyTCP Timeout

Delay Sequence: 1, 2, 4 seconds

tcp half close
net_pyTCP Half-close

send() will fail;

recv() will be ok

tcp msl maximum segment lifetime
net_pyTCP MSL (Maximum Segment Lifetime)
  • MSL is the maximum time that a segment might expect to live on the Internet while moving between the two hosts of a connection.
  • When TCP performs an active close, and sends the final ACK, that connection must stay in the TIME_WAIT state for twice the MSL.
  • Prevents delayed segments from an earlier incarnation of the same connection (srcIP,srcPort,destIP,destPort) from being interpreted as part of the new connection
tcp fin wait 2
net_pyTCP FIN_WAIT_2
  • It is possible to stay in this state forever. Why?