Data Networking Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 320
At a glance
Powered by AI
The document discusses authentication protocols like Kerberos and public-key cryptography. It explains how Kerberos works in detail with examples involving clients (Alice, Bob) and servers (Authentication Server, Ticket Granting Server).

The main components of the Kerberos authentication protocol are the Authentication Server (AS), Ticket Granting Server (TGS) and clients/servers like Alice and Bob. The AS and TGS handle authentication and issuing of tickets while clients and servers participate in the authentication process.

When Alice wants to access Bob, she first authenticates with the AS. The AS then provides her a ticket to authenticate with the TGS, which issues her a ticket granting access to Bob. Alice then presents this ticket to Bob to be granted access.

EEEN30024

Data Networking

images courtesy Vector Ltd, Kurose & Ross


EEEN30024 Lecture 1 1

Course Aims

 The broad aims are to provide an understanding


of the core concepts and fundamental principles
of the operation of computer and embedded
systems networks

– for computer networks the focus will be on


TCP/IP

– for embedded systems networks, selected


examples that are widely-used in industry will
be covered
2
EEEN30024 Lecture 1
Assessment
Examination (80%)
– 4 questions in 3 hours

Coursework (20%)
• consisting of 2 Labs with 1 submission
• individual, in-lab marked
• Important! You will need to bring your PIC
microcontroller and I/O boards

• lab days: check your timetable

3
EEEN30024 Lecture 1

Timetable

Lectures and Labs: days, times, locations:

Lectures Labs

Check your timetable!

4
EEEN30024 Lecture 1
Style
 Handouts will be given out
– set of slides to be used as lecture notes
– appendix material is examinable unless specifically
stated as excluded
– example sheets – these will be provided on Blackboard

 Learning outcomes/resources
– useful for revision, highlight what you should know after
the lecture; pointers to books and web material

 Notes
– sometimes I won’t finish a lecture but will expect you to
read and understand it all
– sometimes I will ask quiz-style questions in class to
check your understanding

5
EEEN30024 Lecture 1

Resources
 The course unit has been prepared with reference
to:
– James F. Kurose & Keith W. Ross, Computer Networking: A
Top Down Approach, 6th edition, Pearson 2012
– William Stallings, Data and Computer Communications, 9th
Edition, Prentice Hall

thanks and acknowledgement go to Kurose, Ross and


Stallings who, with permission, provided course
materials adapted for use with this course

 Lectures will include references to where material


can be found in these textbooks
 Blackboard and Web resources will be indicated as
appropriate

6
EEEN30024 Lecture 1
Plan – subject to change

1– Introduction – Internet
2– Application Layer
3– Transport Layer 1
4– Transport Layer 2
5– Network Layer 1
6– Network Layer 2
7– Network Layer 3
8– Data Link Layer 1
9– Data Link Layer 2
10 – Data Link Layer 3

7
EEEN30024 Lecture 1

Plan – subject to change


11 – Embedded Systems Networks
12 – Asynchronous Serial Networks
13 – Synchronous Serial Networks
14 – CAN, LIN
15 – Coding of Digital Data
16 – Error Detection/Correction
17 – Network Security 1
18 – Network Security 2
19 – Network Security 3

+ guest/invited industry lecture(s).

8
EEEN30024 Lecture 1
A Note About Units...
• Bits/Bytes : • Bandwidth :
– Bits denoted by “b” – uses powers of 10
– Bytes denoted by “B” – tied to MHz which is
– Mb = megabits, 106 hertz
– MB = megabytes – bandwidth of 1 Mbps =
– Kb = kilobits, 106 bits per second
– KB = kilobytes

• ‘K’ and ‘M’ : • Messages


– Mega = 220, Kilo = 210 – use powers of 2
– Mega = 106, Kilo = 103 – tied to computer memory
– in questions it will be measures in powers of 2
made clear which ones – packet/file/message of 1 Mb
are to be used. = 220 bits

9
EEEN30024 Lecture 1

Lecture 1
Introduction
Learning Outcomes
– big-picture view of the Internet
– packet switching and circuit switching
– protocol stacks

Learning Resources
 K&R – sections 1.1, 1.2.1,
1.3.1 and 1.5
 K&R Website for applets:
http://wps.pearsoned.com/ecs_kurose_compnetw_6/216/55463/14198700.cw/

10
EEEN30024 Lecture 1
• How does an application
running on Host 1 “talk” to
Example Network another running on Host 2 ?
Or Host 3 ? Or any other ‘node’
connected to the network ?

• How to analyze/design/build
such networks ?

• Each node needs


networking software.

11
EEEN30024 Lecture 1

Network Software
We shall take a top-down view : simplified 5-layer
model

• network software is
organised as a layered stack
application
• we shall examine each layer
starting from the top transport
• most of the attention will be • each layer consists of
on layers above the physical network one or more protocols
layer
data link • a protocol is a set of
• the physical layer will be rules for exchanging
mentioned later data
physical

• How to make sense of this ?


• the Internet is a good place to start !
12
EEEN30024 Lecture 1
The Internet: a “nuts and bolts” view
PC  millions of connected Mobile network
server computing devices:
Global ISP
hosts = end systems
wireless
laptop -running network programs
cellular
handheld Home network

 communication links Regional ISP


 fiber, copper, radio,
access satellite
points
 transmission rate = Institutional network
wired
links bandwidth

 routers: forward packets


router (chunks of data)

13
EEEN30024 Lecture 1

The Internet: “nuts and bolts” view


 protocols control sending,
receiving of msgs
 e.g., TCP, IP, HTTP, FTP, etc.
 each has its own API*
 Internet: “network of
networks”
 loosely hierarchical
 Internet standards
 IETF: Internet Engineering
Task Force
- a standards organisation
 Standards captured as
‘RFC’s: RFC = Request for
comments * API = Application Programming
Interface 14
EEEN30024 Lecture 1
The Internet: a network of networks
This image cannot currently be display ed.

 mesh of interconnected
routers
 fundamental question:
how is data transferred
through the net?
 circuit switching:
dedicated circuit per
call: telephone
network
 packet-switching:
data sent through
net in discrete
“chunks”
15
EEEN30024 Lecture 1

Circuit Switching

end-end resources are


reserved for a "call"
 link bandwidth,
switch capacity
 dedicated resources:
no sharing
 circuit-like (guaranteed)
performance
 call setup required

16
EEEN30024 Lecture 1
Circuit Switching

network resources
(e.g. bandwidth)
divided into "pieces" :
 pieces allocated to
calls
 resource piece idle if
not used by owning
call (no sharing)
 dividing link
bandwidth into
"pieces"
 frequency division
 time division
17
EEEN30024 Lecture 1

Circuit Switching:
FDM and TDM
Example:
FDM
4 users

frequency

time

TDM

frequency

time
18
EEEN30024 Lecture 1
Circuit Switching:
Numerical example
 How long does it take to send a file of 640,000 bits
from host A to host B over a circuit-switched network?
 all link speeds: 1.536 Mbps
 each link uses TDM with 24 slots/sec
 500 msec to establish end-to-end circuit

• Each circuit has a transmission rate* of 1.536Mbps/24


= 64kbps, so it takes 640,000/64kbps = 10s to
transmit plus 0.5s set-up time = 10.5s.
– transmission time same if circuit passed through one link or
100 links (ignoring any propagation delays)

* "M" means 106 here.


19
EEEN30024 Lecture 1

Packet Switching
each end-to-end data stream resource contention:
divided into packets  aggregate resource demand
 packets share network can exceed amount
resources available
 each packet uses full link  congestion: packets queue,
bandwidth wait for link use
 resources used as needed  store and forward: packets
move one hop at a time
 node receives complete
packet before forwarding

Bandwidth division into


“pieces”
Dedicated allocation
Resource reservation

20
EEEN30024 Lecture 1
Packet Switching:
Statistical Multiplexing
100 Mb/s C
A Ethernet statistical multiplexing

1.5 Mb/s
B
router:queue of packets link
waiting for output
link
host
D E

 sequence of A & B packets has no fixed timing pattern


 bandwidth shared on demand: statistical multiplexing.
 Contrast with TDM: each host gets same slot in revolving
TDM frame.
21
EEEN30024 Lecture 1

Packet-switching:
store-and-forward
L
R R R

 takes L/R seconds to Example:


transmit (push out)  L = 7.5 Mbits
packet of L bits on to  R = 1.5 Mbps
link at R bps
 transmission delay =
 store and forward: 15 sec
entire packet must
arrive at router before
it can be transmitted
on next link
 delay = 3L/R
(assuming zero more on delay later
propagation delay)
22
EEEN30024 Lecture 1
Packet switching versus circuit
switching
Packet switching allows more users to use the network!

Example:
 1 Mb/s link
 each user: N
• 100 kb/s when “active”
users
• active 10% of time 1 Mbps link
 circuit-switching:
 10 users
 packet switching:
Assuming a group of 35 users,
 can potentially support a
larger number of users with each user active for 10% of
 depending on the demand the time, probability calculations
tell us the likelihood of 11 or
more simultaneously active
users is very small.
23
EEEN30024 Lecture 1

Packet switching versus


circuit switching
Packet Switching
 great for statistically ‘bursty’ data
 resource sharing
 simpler, no call setup
 excessive congestion: packet delay and loss
 protocols needed for reliable data transfer,
congestion control
 Q: How to provide circuit-like behavior?
 bandwidth guarantees needed for audio/video apps
 possible to set up a Virtual Circuit using a packet
switched network
 an important topic in its own right
 discussed later
24
EEEN30024 Lecture 1
The Internet

• Application programs run on hosts and servers


– for example, Web, Mail, Skype, FTP
– applications send messages

• Application software makes use of underlying


network software for transfer of information
– it makes no sense for the application software
to be responsible for the full transfer

• Network software is layered into a hierarchy of


protocols providing different services

25
EEEN30024 Lecture 1

Example: organization of air travel

ticket (purchase) ticket (complain)

baggage (check in) baggage (claim)

gates (load) gates (unload)

runway takeoff runway landing

airplane routing airplane routing


airplane routing

 a series of steps

26
EEEN30024 Lecture 1
Layering of airline
functionality
ticket (purchase) ticket (complain) ticket

baggage (check in) baggage (claim) baggage

gates (load) gates (unload) gate

runway (takeoff) runway (land) takeoff/landing

airplane routing airplane routing airplane routing airplane routing airplane routing

departure intermediate air-traffic arrival


airport control centers airport

Layers: each layer implements a service


– via its own internal-layer actions
– relying on services provided by layer below

27
EEEN30024 Lecture 1

Why layering?
Dealing with complex systems:
 explicit structure allows identification,
relationship of complex system’s pieces
 layered reference model for discussion
 modularization eases maintenance, updating
of system
 change of implementation of layer’s service
transparent to rest of system
 e.g. change in gate procedure doesn’t affect
rest of system

28
EEEN30024 Lecture 1
Internet protocol stack
 application: supporting network
applications application
 FTP, SMTP, HTTP
 transport: process-process data transport
transfer
 TCP, UDP
network
 network: routing of datagrams from
source to destination
 IP, routing protocols link
 link: data transfer between
neighboring network elements physical
 Ethernet, 802.111 (WiFi), PPP
 physical: bits “on the wire” 5-layer stack

29
EEEN30024 Lecture 1

ISO/OSI reference model


 presentation: allow applications to
interpret meaning of data, e.g., application
encryption, compression, machine- presentation
specific conventions
 session: synchronization, session
checkpointing, recovery of data transport
exchange
network
 Internet stack “missing” these
layers! link
 these services, if needed, must physical
be implemented in application
 needed? 7-layer stack

30
EEEN30024 Lecture 1
Encapsulation
source
message M application
segment Ht M transport
datagram Hn Ht M network
frame Hl Hn Ht M link
physical
link
physical

switch

destination Hn Ht M network
M application Hl Hn Ht M link Hn Ht M
Ht M transport physical
Hn Ht M network
Hl Hn Ht M link router
physical

31
EEEN30024 Lecture 1

Simple 5-Layer Model


Protocol Data Units

32
EEEN30024 Lecture 1
This course unit
• In this course unit we will consider networks
with reference to the 5-layer model given
earlier
– this is essentially the OSI model with the almost
redundant session and presentation layers
removed
– this provides a useful model for thinking about
networks

• We shall consider TCP (and UDP) as practical


examples of the transport layer and IP for the
internetworking aspects of the network layer
33
EEEN30024 Lecture 1
Lecture 2:
Application layer

Learning Outcomes: application


 Understand the principles of
network applications transport
 Examine some example
applications: network
 Web and HTTP, FTP, DNS
 Understand the transport link
layer needs of network
applications
physical

1
EEEN30024 Lecture 2

Some network
applications
 e-mail  voice over IP
 web  real-time video
 instant messaging conferencing
 remote login  cloud computing
 P2P file sharing  …
 multi-user network  …
games 

 streaming stored
video (YouTube)

2
EEEN30024 Lecture 2
Creating a network
application applicatio
n
transport
network

write programs that data link


physical

 run on (different) end


systems
 communicate over network
 e.g., web server software
communicates with browser
software
No need to write software applicatio
n
transport
for network-core network
data link
applicatio
n
devices physical
transport
network
 network-core devices do data link
physical
not run user applications
 applications on end systems
allows for rapid app
development, propagation
3
EEEN30024 Lecture 2

Application architectures

 client-server
 peer-to-peer (P2P)
 hybrid of client-server and P2P

 Our focus will be client-server

EEEN30024 Lecture 2 4
Client-server architecture
server:
 always-on host
 permanent IP address
 server farms for scaling
clients:
 communicate with server
 may be intermittently
connected
client/server  may have dynamic IP
addresses
 do not communicate
directly with each other

EEEN30024 Lecture 2 5

Processes
communicating
process: a program client process: process
running within a host. that initiates
 within same host, two
communication
processes server process:
communicate using process that waits to
inter-process be contacted
communication
(defined by OS).  aside: applications
 processes in different with P2P architectures
hosts communicate by have client processes
exchanging messages & server processes

6
EEEN30024 Lecture 2
Sockets
 process sends/receives
host or
messages to/from its socket host or
server
server
 socket analogous to door
 sending process shoves controlled by
message out door process
app developer
process
 sending process relies on socket
socket
transport infrastructure
TCP with
on other side of door TCP with
Internet buffers,
buffers,
which brings message to variables variables
socket at receiving
process
controlled
by OS
 API:
 choice of transport protocol
 choice of parameters

EEEN30024 Lecture 2 7

Addressing processes
 to receive messages,  identifier includes both IP
process must have an address and port numbers
identifier associated with process on
host.
 host device has a unique
32-bit IP address  example port numbers:
 Q: does IP address of host  HTTP server: 80
on which process runs  Mail server: 25
suffice for identifying the  to send HTTP message to
process? the manchester.ac.uk web
 A: No, many processes server:
can be running on same  IP address:
host 130.88.203.13
 Port number: 80

8
EEEN30024 Lecture 2
Application layer protocol
defines
 types of messages public-domain
exchanged, protocols:
 e.g., request, response  defined in RFCs
 message syntax:  allows for
 what fields in messages interoperability
& how fields are
 e.g., HTTP, SMTP
delineated
 message semantics proprietary protocols:
 meaning of information  e.g., Skype
in fields
 rules for when and
how processes send &
respond to messages
9
EEEN30024 Lecture 2

What transport service


properties does an application
need?
Reliability (no data loss, and
data arrives in correct
order) Throughput
 some apps (e.g., audio)  some apps (e.g.,
can tolerate some loss multimedia) require
 other apps (e.g., file minimum amount of
transfer, telnet) require throughput to be "effective"
100% reliable data transfer  other apps ("elastic apps")
make use of whatever
Timing throughput they get
 some apps (e.g.,
Internet telephony,
interactive games) Security
require low delay to be  encryption, data integrity
"effective"  provided by e.g. SSL

10
EEEN30024 Lecture 2
Transport service requirements
of common apps

Application Data loss Throughput Time Sensitive

file transfer no loss elastic no


e-mail no loss elastic no
Web documents no loss elastic no
real-time audio/video loss-tolerant audio: 5kbps-1Mbps yes, 100’s msec
video:10kbps-5Mbps
stored audio/video loss-tolerant same as above yes, few secs
interactive games loss-tolerant few kbps up yes, 100’s msec
instant messaging no loss elastic yes and no

EEEN30024 Lecture 2 11

Internet transport protocols:


services
TCP service: UDP service:
 connection-oriented: setup  unreliable data transfer
required between client and between sending and
server processes receiving process
 reliable transport between  does not provide:
sending and receiving connection setup,
process reliability, flow control,
 flow control: sender won’t congestion control,
overwhelm receiver timing, throughput
 congestion control: throttle guarantee, or security
sender when network
overloaded Q: why bother? Why is
 does not provide: timing, there a UDP? What is
minimum throughput meant by 'reliability'
guarantees, security anyway?
12
EEEN30024 Lecture 2
Internet apps:
application, transport protocols
Application Underlying
Application layer protocol transport protocol

e-mail SMTP [RFC 2821] TCP


remote terminal access Telnet [RFC 854] TCP
Web HTTP [RFC 2616] TCP
file transfer FTP [RFC 959] TCP
streaming multimedia HTTP (e.g., YouTube), TCP or UDP
RTP [RFC 1889]
Internet telephony SIP, RTP, proprietary
(e.g., Skype) typically UDP

EEEN30024 Lecture 2 13

HTTP
overview
HTTP: hypertext
transfer protocol
 Web’s application layer PC running
protocol Internet Explorer
 client/server model
 client: browser that
requests, receives, Server
"displays" Web running
objects Apache Web
server
 server: Web server
sends objects* in
Mac running
response to requests Safari

 *objects = HTML pages,


images, JavaScript, ...
14
EEEN30024 Lecture 2
HTTP overview (continued)
Uses TCP: HTTP is "stateless"
 client initiates TCP  server maintains no
connection (creates information about
socket) to server, port 80 past client requests
 server accepts TCP
connection from client aside
protocols that maintain
 HTTP messages "state" are complex!
(application-layer protocol
 past history (state) must
messages) exchanged
be maintained
between browser (HTTP
client) and Web server  if server/client crashes,

(HTTP server) their views of "state"


may be inconsistent,
 TCP connection closed
must be reconciled

15
EEEN30024 Lecture 2

HTTP request
message
 two types of HTTP messages: request,
response
 HTTP request message: carriage return character
 ASCII (human-readable format) line-feed character
request line
(GET, POST, GET /index.html HTTP/1.1\r\n
HEAD commands) Host: www-net.cs.umass.edu\r\n
User-Agent: Firefox/3.6.10\r\n
Accept: text/html,application/xhtml+xml\r\n
header Accept-Language: en-us,en;q=0.5\r\n
lines Accept-Encoding: gzip,deflate\r\n
Accept-Charset: ISO-8859-1,utf-8;q=0.7\r\n
carriage return, Keep-Alive: 115\r\n
Connection: keep-alive\r\n
line feed at start
\r\n
of line indicates
end of header lines
EEEN30024 Lecture 2 16
HTTP request message:
general format

request
line

header
lines

body

EEEN30024 Lecture 2 17

HTTP response message


status line
(protocol
status code HTTP/1.1 200 OK\r\n
status phrase) Date: Sun, 26 Sep 2010 20:09:20 GMT\r\n
Server: Apache/2.0.52 (CentOS)\r\n
Last-Modified: Tue, 30 Oct 2007 17:00:02
GMT\r\n
header ETag: "17dc6-a5c-bf716880"\r\n
Accept-Ranges: bytes\r\n
lines Content-Length: 2652\r\n
Keep-Alive: timeout=10, max=100\r\n
Connection: Keep-Alive\r\n
Content-Type: text/html; charset=ISO-8859-
1\r\n
\r\n
data, e.g., data data data data data ...
requested
HTML file
EEEN30024 Lecture 2 18
User-server state:
cookies
example:
many Web sites use
cookies  Susan always access

four components: Internet from PC


1) cookie header line of  visits specific e-
HTTP response commerce site for first
message
time
2) cookie header line in
HTTP request  when initial HTTP
message requests arrives at
3) cookie file kept on
user’s host, managed
site, site creates:
by user’s browser  unique ID
4) back-end database at  entry in backend
Web site
database for ID
19
EEEN30024 Lecture 2

Cookies: keeping "state"


(cont.)
client server
ebay 8734 usual http request Amazon server
msg creates ID create
cookie file usual http response 1678 for user entry
Set-cookie: 1678
ebay 8734
amazon 1678
usual http request
msg cookie- access
cookie: 1678 specific
one week later: usual http response action backend
msg database
access
ebay 8734 usual http request
amazon 1678 msg cookie-
cookie: 1678 specific
usual http response action
msg
20
EEEN30024 Lecture 2
Cookies
(continued)
what cookies can
aside
bring:
 authorization cookies and privacy:
 shopping carts  cookies permit sites to
learn a lot about you
 recommendations
 you may supply name
 user session state (Web
and e-mail to sites
e-mail)

how to keep "state":


 protocol endpoints: maintain state at
sender/receiver over multiple
transactions
 cookies: http messages carry state

21
EEEN30024 Lecture 2

DNS: Domain Name


System
people: many identifiers: Domain Name System:
 SSN, name, passport  distributed database
# implemented in hierarchy of
Internet hosts, routers: many name servers
 IP address (32 bit) -  application-layer protocol
used for addressing host, routers, name servers
datagrams to communicate to resolve
 "name", e.g., names (address/name
www.yahoo.com - translation)
used by humans  note: core Internet
Q: map between IP address function, implemented as
and name, and vice application-layer protocol
versa ?  complexity at network’s
"edge"
22
EEEN30024 Lecture 2
DNS
DNS services Why not centralize DNS?
 hostname to IP  single point of failure
address translation  traffic volume
 host aliasing  distant centralized
 Canonical, alias database
names
 maintenance
 mail server aliasing
 load distribution
doesn’t scale!
 replicated Web
servers: set of IP
addresses for one
canonical name

23
EEEN30024 Lecture 2

Distributed, Hierarchical
Database
Root DNS Servers

com DNS servers org DNS servers edu DNS servers

pbs.org poly.edu umass.edu


yahoo.com amazon.com
DNS servers DNS serversDNS servers
DNS servers DNS servers

client wants IP for www.amazon.com; 1st approx:


 client’s local DNS server queries a root server to find com DNS
server
 local DNS server then queries com DNS server to get
amazon.com DNS server
 finally, local DNS server queries amazon.com DNS server to get
IP address for www.amazon.com
EEEN30024 Lecture 2 24
DNS: Root name
servers
 contacted by local name server that can not resolve name
 root name server:
 contacts authoritative name server if name mapping not
known
 gets mapping
 returns mapping to local name server
a Verisign, Dulles, VA
c Cogent, Herndon, VA (also LA)
d U Maryland College Park, MD k RIPE London (also 16 other locations)
g US DoD Vienna, VA
h ARL Aberdeen, MD i Autonomica, Stockholm (plus
j Verisign, ( 21 locations) 28 other locations)
e NASA Mt View, CA m WIDE Tokyo (also Seoul,
f Internet Software C. Palo Alto, Paris, SF)
CA (and 36 other locations)

13 root name
servers
b USC-ISI Marina del Rey, CA
l ICANN Los Angeles, CA worldwide

25
EEEN30024 Lecture 2

TLD and Authoritative


Servers
Top-level domain (TLD) servers:
 responsible for com, org, net, edu, aero, jobs,
museums, and all top-level country domains, e.g.: uk,
fr, ca, jp
 Network Solutions maintains servers for com TLD
 Educause for edu TLD

Authoritative DNS servers:


 organization’s DNS servers, providing authoritative
hostname to IP mappings for organization’s servers
(e.g., Web, mail).
 can be maintained by organization or service provider

EEEN30024 Lecture 2 26
Local Name Server

 does not strictly belong to hierarchy


 each ISP (residential ISP, company,
university) has one
 also called "default name server"
 when host makes DNS query, query is sent to
its local DNS server
 acts as proxy, forwards query into hierarchy

EEEN30024 Lecture 2 27

root DNS server


DNS name
resolution example 2
3
TLD DNS server
4
 host at cis.poly.edu
wants IP address for 5
gaia.cs.umass.edu local DNS server
dns.poly.edu
7 6
1
iterated query: 8

 contacted server replies


authoritative DNS server
with name of server to dns.cs.umass.edu
contact requesting host
 "I don’t know this name, cis.poly.edu
but ask this server"
 note: step 1 in this example is gaia.cs.umass.edu
recursive, not iterative –see next
slide; in practice DNS uses both
types of query 28
EEEN30024 Lecture 2
DNS name root DNS server

resolution
example 2 3

recursive query: 7 6

 puts burden of TLD DNS server


name resolution on
contacted name local DNS server
server dns.poly.edu 5 4

 heavy load? 1 8

 once a name server authoritative DNS server


learns a mapping, it is dns.cs.umass.edu
cached in memory requesting host
cis.poly.edu
 cache entries
eventually timeout gaia.cs.umass.edu

EEEN30024 Lecture 2 29

DNS protocol, messages


DNS protocol : query and reply messages, both
with same message format

msg header
 identification: 16 bit #
for query, reply to
query uses same #
 flags:
 query or reply
 recursion desired
 recursion available
 reply is authoritative

30
EEEN30024 Lecture 2
DNS protocol, messages

Name, type fields


for a query

RRs in
response
to query
records for
authoritative servers

additional “helpful”
info that may be used

31
EEEN30024 Lecture 2

Review Questions &


Wireshark Exercises

 To help you get a better understanding of


HTTP and the DNS try Wireshark Exercises 1
and 2 on Blackboard.

 Try the Review Questions for Lectures 01-02


on Blackboard.

32
EEEN30024 Lecture 2
Lecture 2: Summary
 application  specific protocols:
architectures HTTP, FTP, DNS
 client-server  typical request/reply
 P2P message exchange:
 hybrid  client requests info or
 application service service
requirements:  server responds with
data, status code
 reliability, bandwidth,
delay  message formats:
 Internet transport  headers: fields giving
info about data
service model
 data: info being
 connection-oriented,
communicated
reliable: TCP
 unreliable, datagrams:
UDP 33
EEEN30024 Lecture 2

Appendix (examinable)
FTP: the file transfer protocol
This image cannot currently be display ed.

FTP file transfer


FTP FTP
user client server
interface
user
at host remote file
local file system
system

 transfer file to/from remote host


 client/server model
 client: side that initiates transfer (either to/from
remote)
 server: remote host
 ftp: RFC 959
 ftp server: port 21
34
EEEN30024 Lecture 2
FTP: separate control, data
connections
TCP control
 FTP client contacts FTP connection,
server at port 21, TCP is server port 21
transport protocol
 client authorized over control TCP data connection,
connection FTP server port 20 FTP
 client browses remote client server
directory by sending
 server opens another TCP
commands over control
data connection to transfer
connection.
another file.
 when server receives file
 control connection: "out of
transfer command, server
band"
opens 2nd TCP connection
(for file) to client  FTP server maintains
"state": current directory,
 after transferring one file,
earlier authentication
server closes data
connection. 35
EEEN30024 Lecture 2

FTP commands,
responses
sample commands: sample return codes
 sent as ASCII text over  status code and phrase
control channel (as in HTTP)
 USER username  331 Username OK,
 PASS password password required
 125 data connection
 LIST return list of file in
already open;
current directory
transfer starting
 RETR filename retrieves  425 Can’t open data
(gets) file connection
 STOR filename stores  452 Error writing
(puts) file onto remote file
host

36
EEEN30024 Lecture 2
Lecture 3:
Transport Layer (1/2)

Learning
Outcomes:  understand how
 understand transport layer
principles behind protocols in the
transport layer Internet work:
services:  UDP: connectionless
 multiplexing/ transport
demultiplexing  TCP: connection-oriented
transport
 reliable data
transfer

EEEN30024 Lecture 3 1

Transport vs
network layer

 transport layer: Business analogy:


logical communication company staff send letters to staff
between processes in other branches
 processes = staff members
 relies on, enhances,
network layer services  appl’n messages = letters in
envelopes
 hosts = company offices
 network layer:
 transport protocol = company
logical communication secretaries who distribute
between hosts letters to staff
 moves data from host  network-layer protocol = postal
to host service

EEEN30024 Lecture 3 2
Internet transport-layer protocols
reliable, in-order applicatio
 n
transport
delivery (TCP) network
data link
physical network
 congestion control data link
physical network
data link
 flow control physical

 connection setup
 unreliable, unordered network
data link
physical
delivery: UDP
network
data link
physical
 no-frills extension of network
data link
applicatio
"best-effort" IP physical network n
data link transport

 services not available: physical network


data link
physical
 delay guarantees
 bandwidth guarantees
Protocol data units at the transport
layer are called segments.
EEEN30024 Lecture 3 3

Multiplexing/demultiplexing
Demultiplexing at rcv host: Multiplexing at send host:
gathering data from multiple
delivering received segments
sockets, enveloping data with
to correct socket
header (later used for
demultiplexing)
= socket, = process, e.g.
(IP addr + port) web, ftp, …

application P3 P1
P1 application P2 P4 application

transport transport transport

network network network

link link link

physical physical physical

host 2 host 3
host 1
EEEN30024 Lecture 3 4
How demultiplexing
works
 host receives IP
datagrams 32 bits
 each datagram has source source port # dest port #
IP address, destination IP
address
other header fields
 each datagram carries 1
transport-layer segment
 each segment has source,
destination port number application
 host uses IP addresses & data
port numbers to direct (message)
segment to appropriate
socket
 port is 16-bit number TCP/UDP segment format
ranging from 0 - 65535
EEEN30024 Lecture 3 5

Connectionless
demultiplexing
 when host receives
 create sockets with host-
UDP segment:
local port numbers*:
DatagramSocket mySocket1 = new  checks destination port
DatagramSocket(12534); number in segment
DatagramSocket mySocket2 = new  directs UDP segment to
DatagramSocket(12535); socket with that port
number
 when creating datagram
to send into UDP socket,  IP datagrams with
must specify different source IP
addresses and/or
(dest IP address, dest port number)
source port numbers
*see Appendix for programming examples directed to the same
socket
EEEN30024 Lecture 3 6
Connectionless
demultiplexing
DatagramSocket serverSocket = new DatagramSocket(6428);

P2 P1
P1
P3

SP: 6428 SP: 6428


DP: 9157 DP: 5775

SP: 9157 SP: 5775


client DP: 6428 DP: 6428 Client
server
IP: A IP: C IP:B

SP provides "return address"

EEEN30024 Lecture 3 7

Connection-oriented
demultiplexing
 TCP socket identified  server host may
by 4-tuple: support many
 source IP address simultaneous TCP
 source port number sockets:
 dest IP address  each socket identified by
 dest port number its own 4-tuple
 recv host uses all four  web servers have
values to direct different sockets for
segment to each connecting client
appropriate socket

EEEN30024 Lecture 3 8
Connection-oriented
demultiplexing

P1 P4 P5 P6 P2 P1P3

SP: 5775
DP: 80
S-IP: B
D-IP:C

SP: 9157 SP: 9157


client DP: 80 DP: 80 client
server
IP: A S-IP: A
IP: C S-IP: B IP:B
D-IP:C D-IP:C

EEEN30024 Lecture 3 9

Connection-oriented
demultiplexing :
Multi-Threaded Web Server

P1 P4 P2 P1P3

SP: 5775
DP: 80
S-IP: B
D-IP:C

SP: 9157 SP: 9157


client DP: 80 DP: 80 client
server
IP: A S-IP: A
IP: C S-IP: B IP:B
D-IP:C D-IP:C

EEEN30024 Lecture 3 10
UDP:
User Datagram Protocol [RFC 768]
 "no frills", "bare bones"
Internet transport Why is there a UDP?
protocol
 no connection
 "best effort" service, UDP establishment (which can
segments may be: add delay)
 lost  simple: no connection
 delivered out of order state at sender, receiver
to app  small segment header
 connectionless:  no congestion control:
 no handshaking UDP can blast away as
between UDP sender, fast as desired
receiver
 each UDP segment
handled independently
of others
EEEN30024 Lecture 3 11

UDP: more
 often used for 32 bits
streaming
source port # dest port #
multimedia apps Length, in
bytes of UDP length checksum
 loss tolerant
segment,
 rate sensitive including
header
 other UDP uses
 DNS
Application
 SNMP data
 to facilitate reliable (message)
transfer over UDP:
add reliability at
UDP segment format
application layer
 but its hard work !
EEEN30024 Lecture 3 12
UDP checksum
Goal: detect "errors" (e.g., flipped bits) in
transmitted segment

Sender: Receiver:
 treat segment contents  compute checksum of
as sequence of 16-bit received segment
integers  check if computed
 checksum: addition (1’s checksum correct:
complement sum) of  NO - error detected
segment contents  YES - no error detected.
 sender puts checksum But maybe errors
value into UDP nonetheless?
checksum field More later ….

EEEN30024 Lecture 3 13

Internet Checksum Example


 Note: when adding numbers, a carryout
from the most significant bit needs to
be added to the result
 Example: add two 16-bit integers

1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0
1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Wraparound 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1
carry and add
sum 1 1 0 1 1 1 0 1 1 1 0 1 1 1 1 0 0
checksum 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 1

EEEN30024 Lecture 3 14
Principles of Reliable
Data Transfer
 Relevant in application, transport, link layers

data sending receiver data application


process process layer

segment reliable data reliable data segment


transport
transfer protocol transfer protocol layer

packet unreliable channel packet


network
layer

 characteristics of unreliable channel determines complexity of


reliable data transfer protocol
 in the diagram communication can be either
 simplex –data sent in only one direction, e.g. either L-R, or R-L
 half-duplex –data sent in both directions but only one direction at a time
 full-duplex –data sent in both directions simultaneously

15
EEEN30024 Lecture 3

Principles of Reliable
data transfer
Assumptions:
 consider only unidirectional data transfer
 but control info will flow on both directions!
 underlying channel unreliable
 may corrupt bits in packet
 so use checksum to detect bit errors
 acknowledgements (ACKs/NAKs):
 ACK: receiver explicitly tells sender that pkt received
OK
 NAK: tells sender that pkt received not OK
 sender sends one packet, then waits for
receiver response
EEEN30024 Lecture 3 16
Protocol in Action
sender receiver
send pkt
rcv pkt
send ACK/NAK
rcv ACK/NAK

send pkt
rcv pkt
send ACK/NAK
rcv ACK/NAK

send pkt
rcv pkt
send ACK/NAK
rcv ACK/NAK

Note: NAKs
This is called a Stop-and-Wait
result in pkt
protocol
retransmission
EEEN30024 Lecture 3 17

Principles of Reliable
data transfer
What happens if Handling duplicates:
ACK/NAK corrupted or  sender retransmits current pkt
not received? if ACK garbled
 sender doesn’t know what  solution: sender adds sequence
happened at receiver! number to each pkt
 initially 0 and 1
 can’t just retransmit:
possible duplicate  receiver can now identify and
discard duplicate pkt
 receiver uncertain whether
 if sender receives NACK for pkt 0 it
the retransmitted pkt is a
will retransmit it. Once ACK is
retransmit or a new pkt received correctly pkt 1 is
Protocols based on transmitted.
retransmission are called  similarly if receiver receives corrupted
pkt 0 it will (re)transmit NAK
ARQ:
Automatic Repeat reQuest ARQ-based protocols are characterised
by acknowledgements, timeouts and
re-transmissions
EEEN30024 Lecture 3 18
Principles of Reliable
data transfer
ACKs and NAKs :
 If the sequence number is included in the ACK, we
can do away with NAKs:

 in normal operation a receiver will send ACK0 in


response to pkt 0, and an ACK1 in response to pkt
1.
 if a pkt is corrupted the receiver will retransmit
the ACK for the last correctly received pkt
 e.g. if sender receives an ACK0 after transmitting
pkt 1 it knows pkt 1 was not correctly received so
will retransmit it. Once ACK1 is received correctly
the next pkt 0 is transmitted.

EEEN30024 Lecture 3 19

Dealing with errors and


loss
Underlying channel can also
lose packets (data or Approach: sender waits
ACKs) "reasonable" amount of time
 checksum, seq. #, for ACK
ACKs, retransmissions  retransmits if no ACK
will be of help, but not received in this time
enough
 if pkt (or ACK) just delayed
"reasonable" amount of time (not lost):
must include at least  retransmission will be
 the RTT of the channel duplicate, but use of seq.
 time to process pkts at #’s already handles this
each end  receiver must specify seq
 difficult to estimate # of pkt being ACKed
unless channel
 requires countdown timer
characteristics are known
RTT = round trip time
EEEN30024 Lecture 3 20
Discussion
Sender: Receiver:
 seq # added to pkt  must check if received
and ACKs packet is duplicate
 two seq. #’s (0,1)  receiver "knows"
will suffice. whether 0 or 1 is the
next expected pkt seq
 must check if #
received ACK is out  note: receiver can not
of order or is know if its last ACK
corrupted received OK at sender
 receiver must
"remember" whether
"current" pkt has 0
or 1 seq. #
EEEN30024 Lecture 3 21

Protocol in action

EEEN30024 Lecture 3 22
Protocol in action

EEEN30024 Lecture 3 23

Performance

 protocol works, but performance is terrible!


 ex: 1 Gbps link, 15 ms propagation delay, 8000
bit packet:

 U sender: utilization – fraction of time sender busy sending

 RTT = 2 x Tp, where Tp is the propagation delay


 if RTT=30 msec, 1KB pkt every 30 msec -> 33kB/sec
throughput over 1 Gbps link
 network protocol limits use of physical resources!
EEEN30024 Lecture 3 24
Stop-and-Wait operation

sender receiver
first packet bit transmitted, t = 0
last packet bit transmitted, t = L / R

first packet bit arrives


RTT last packet bit arrives, send ACK

ACK arrives, send next


packet, t = RTT + L / R

EEEN30024 Lecture 3 25

Pipelined protocols
data

Stop-and-Wait
ACK

data

Pipelining
ACKs

Pipelining:
 sender allows multiple, "in-flight", yet-to-be-
acknowledged packets
 range of sequence numbers must be increased
 buffering required at sender and/or receiver
 two generic forms of ARQ-based pipelined
protocols: go-Back-N, selective repeat
EEEN30024 Lecture 3 26
Pipelining: increased utilization
sender receiver
first packet bit transmitted, t = 0
last bit transmitted, t = L / R

first packet bit arrives


RTT last packet bit arrives, send ACK
last bit of 2nd packet arrives, send ACK
last bit of 3rd packet arrives, send ACK
ACK arrives, send next
packet, t = RTT + L / R

Increase utilization
by a factor of 3!

EEEN30024 Lecture 3 27

Lecture 3: Summary

 principles behind
transport layer services: Next:
 multiplexing,  flow control
demultiplexing  TCP in detail
 reliable data transfer
 instantiation and
implementation in the
Internet
 UDP
 TCP

EEEN30024 Lecture 3 28
Appendix: (non-examinable)
Socket programming
Goal: see how a client/server application that
communicate using sockets is built using Java

Socket API socket


 introduced in BSD4.1 a host-local,
UNIX, 1981 application-created,
 explicitly created, used, OS-controlled interface
released by apps (a "door") into which
 client/server paradigm application process can
 two types of transport both send and
service via socket API: receive messages
to/from another
 unreliable datagram application process
 reliable, byte stream-
oriented

EEEN30024 Lecture 3 29

Socket-programming using TCP


Socket: a door between application process and
end-end-transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one
process to another
controlled by
controlled by process application
application process
developer
developer socket socket
TCP with TCP with controlled by
controlled by
buffers, operating
operating buffers, internet variables system
system variables

host or host or
server server

EEEN30024 Lecture 3 30
Socket programming
with TCP
Client must contact server  when contacted by client,
 server process must first server TCP creates new
be running socket for server process
 server must have created to communicate with client
socket (door) that  allows server to talk
welcomes client’s contact with multiple clients
Client contacts server by:  source port numbers
used to distinguish
 creating client-local TCP
clients)
socket
 specifying IP address,
port number of server application viewpoint
process TCP provides reliable, in-order
 when client creates transfer of bytes ("pipe")
socket: client TCP between client and server
establishes connection to
server TCP EEEN30024 Lecture 3 31

Client/server socket interaction:


TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket

EEEN30024 Lecture 3 32
Stream jargon
 stream is a sequence of
characters that flow into
Client
or out of a process.
process
 input stream is attached
to some input source for
the process, e.g.,
keyboard or socket.
 output stream is
attached to an output
source, e.g., monitor or client TCP
socket. socket

EEEN30024 Lecture 3 33

Socket programming with TCP


Example client-server app:
1) client reads line from standard input
(inFromUser stream) , sends to server via
socket (outToServer stream)

2) server reads line from socket

3) server converts line to uppercase, sends back


to client

4) client reads, prints modified line from socket


(inFromServer stream)

EEEN30024 Lecture 3 34
Example: Java client (TCP)
import java.io.*;
This package defines Socket()
import java.net.*; and ServerSocket() classes
class TCPClient {

public static void main(String argv[]) throws Exception


{
server name,
String sentence; e.g., www.umass.edu
String modifiedSentence;
server port #
create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
create
clientSocket object
of type Socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream());
attached to socket

EEEN30024 Lecture 3 35

Example: Java client (TCP), cont.

create BufferedReader inFromServer =


input stream new BufferedReader(new
attached to socket InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();
send line
to server outToServer.writeBytes(sentence + '\n');

read line modifiedSentence = inFromServer.readLine();


from server
System.out.println("FROM SERVER: " + modifiedSentence);

close socket clientSocket.close();


(clean up behind yourself!)

}
}
EEEN30024 Lecture 3 36
Example:
Java server (TCP)
import java.io.*;
import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception


{
String clientSentence;
String capitalizedSentence;
create
welcoming socket
at port 6789 ServerSocket welcomeSocket = new ServerSocket(6789);

wait, on welcoming while(true) {


socket accept() method
for client contact create, Socket connectionSocket = welcomeSocket.accept();
new socket on return
BufferedReader inFromClient =
create input new BufferedReader(new
stream, attached InputStreamReader(connectionSocket.getInputStream()));
to socket

EEEN30024 Lecture 3 37

Example:
Java server (TCP), cont..
create output
stream,
attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
read in line
from socket clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';


write out line
to socket outToClient.writeBytes(capitalizedSentence);
}
}
} end of while loop,
loop back and wait for
another client connection

EEEN30024 Lecture 3 38
Socket programming with UDP
UDP: no "connection"
between client and
server
application viewpoint:
 no handshaking
 sender explicitly attaches
UDP provides unreliable transfer
IP address and port of of groups of bytes ("datagrams")
destination to each between client and server
packet
 server must extract IP
address, port of sender
from received packet
UDP: transmitted data may
be received out of order,
or lost
EEEN30024 Lecture 3 39

Client/server
socket interaction: UDP
Server (running on hostid) Client

create socket, create socket,


port= x. clientSocket =
serverSocket = DatagramSocket()
DatagramSocket()
Create datagram with server IP and
port=x; send datagram via
read datagram from clientSocket
serverSocket

write reply to
serverSocket
specifying read datagram from
client address, clientSocket
port number close
clientSocket

EEEN30024 Lecture 3 40
Example: Java client (UDP)

Client
process Input: receives
packet (recall
Output: sends thatTCP received
packet (recall “byte stream”)
that TCP sent “byte
stream”)

client UDP
socket

EEEN30024 Lecture 3 41

Example: Java client (UDP)


import java.io.*;
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
create
client socket DatagramSocket clientSocket = new DatagramSocket();

translate InetAddress IPAddress = InetAddress.getByName("hostname");


hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();

EEEN30024 Lecture 3 42
Example:
Java client (UDP), cont.
create datagram
with data-to-send, DatagramPacket sendPacket =
length, IP addr, new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
port
clientSocket.send(sendPacket);
send datagram
to server DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
read datagram
clientSocket.receive(receivePacket);
from server
String modifiedSentence =
new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);


clientSocket.close();
}
}

EEEN30024 Lecture 3 43

Example:
Java server (UDP)
import java.io.*;
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[ ] receiveData = new byte[1024];
byte[ ] sendData = new byte[1024];

while(true)
{
create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
receive
datagram
EEEN30024 Lecture 3 44
Example:
Java server (UDP), cont
String sentence = new String(receivePacket.getData());

get IP addr InetAddress IPAddress = receivePacket.getAddress();


and port #, of
sender int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, sendData.length, IPAddress,
port);
write out
datagram serverSocket.send(sendPacket);
to socket }
} end of while loop,
}
loop back and wait for
another datagram

EEEN30024 Lecture 3 45
Lecture 4: Transport Layer
(2/2)
Learning Outcomes:

 continue study of transport


layer services:
 reliable data transfer
 TCP in detail
• flow control
• connection management
• congestion control

EEEN30024 Lecture 4 1

Pipelined Protocols
data

stop and wait


ACK

data

pipelining
ACKs

pipelining:
 sender allows multiple, "in-flight", yet-to-be-
acknowledged pkts
 range of sequence numbers must be increased
 buffering required at sender and/or receiver
 two generic forms of pipelined protocols:
go-Back-N, Selective Repeat
EEEN30024 Lecture 4 2
Pipelined Protocols
Go-back-N: big picture Selective Repeat: big picture
 sender can have up to  sender can have up to N
N unacknowledged unacknowledged packets
packets in pipeline in pipeline
 receiver sends  receiver sends individual
individual ACK for each ACK for each packet even if
packet there’s a gap
 except when there’s a  sender maintains timer for
gap each unacknowledged
 sender uses cumulative packet
ACKs
 when timer expires,
 sender has timer for retransmit only
oldest unacknowledged unacknowledged packet
packet
 if timer expires,
retransmit all
unacknowledged packets
3
EEEN30024 Lecture 4

Go-Back-N
Sender:
 k-bit seq # in pkt header (thus range of seq #s is 0 -> 2k – 1)
 “window” of up to N, consecutive unack’ed pkts allowed

pkts 9 onwards

pkts 1-8

already ack’ed
window slides left to right in the
diagram

 ACK(n): ACKs are received for all pkts up to and including


seq # n – called a "cumulative ACK"
 may receive duplicate ACKs (see receiver)

EEEN30024 Lecture 4 4
Go-Back-N
Sender:
 single timer used
 timer running for oldest but not yet acked pkt
 if ACK received but there are still additional pkts sent but
not yet acked, the timer is restarted.
 timeout(n): retransmit pkt n and all higher seq # pkts in
window

An example of a sliding window protocol


 For Go-Back-N window size N limited: N <= 2k – 1
-for reasons of flow and congestion control
 window size smaller for Selective Repeat protocol (see
later)

EEEN30024 Lecture 4 5

Go-Back-N

Receiver:
 always send ACK for correctly-received pkt with
highest in-order seq #
 may generate duplicate ACKs
 need only remember next expected seq #

 out-of-order pkt:
 discard (don’t buffer) -> no receiver buffering!
 re-send ACK pkt with highest in-order seq #

EEEN30024 Lecture 4 6
Go-Back-N in action
sender window (N=4) sender receiver
012345678 send pkt0
012345678 send pkt1
012345678 send pkt2 receive pkt0, send ack0
012345678 send pkt3 Xloss receive pkt1, send ack1
(wait)
receive pkt3, discard,
012345678 rcv ack0, send pkt4 (re)send ack1
012345678 rcv ack1, send pkt5 receive pkt4, discard,
(re)send ack1
ignore duplicate ACK receive pkt5, discard,
(re)send ack1
pkt 2 timeout
012345678 re-send pkt2
012345678 re-send pkt3
012345678 re-send pkt4 rcv pkt2, deliver, send ack2
012345678 re-send pkt5 rcv pkt3, deliver, send ack3
rcv pkt4, deliver, send ack4
rcv pkt5, deliver, send ack5

EEEN30024 Lecture 4 7

Go-Back-N

 Limitations of GBN:
 in some scenarios, when window size is large and
delays are long, many pkts can be in the pipeline
 a single pkt error can cause the retransmission of a
large number of pkts –the main limitation
 alternative –a scheme where the sender only
retransmits those pkts that were in error: Selective
Repeat

 See the Go-Back-N protocol applet at :


http://wps.aw.com/aw_kurose_network_5/111/28536/73053
12.cw/index.html

EEEN30024 Lecture 4 8
Selective Repeat
 receiver individually acknowledges all
correctly received pkts
 buffers pkts, as needed, for eventual in-order
delivery to upper layer
 sender only resends pkts for which ACK not
received
 sender timer for each unACKed pkt
 sender window
 N consecutive seq #’s
 again limits seq #s of sent, unACK’ed pkts

EEEN30024 Lecture 4 9

Selective repeat:
sender, receiver windows

pkts ack’ed
by receiver

pkts ack’ed
by receiver

EEEN30024 Lecture 4 10
Selective repeat:
sender, receiver windows
(reading notes to accompany previous slide)
Sender and receiver windows
• size 14 pkts, numbered left-to-right

Sender Window:
Pkts 1,2,5,8: pkts sent but not yet ack’ed
Pkts 3,4,6,7: pkts already ack’ed
Pkts 9-14: pkts usable but not yet sent

Receiver Window:
Pkts 1,4: pkts expected but not yet
received
Pkts 2,3: pkts received out of order, but
already ack’ed
Pkts 5-14: pkts ready to be accepted

EEEN30024 Lecture 4 11

Selective repeat
sender receiver
data from above : pkt n in
 if next available seq # in [rcvbase, rcvbase+N-1]
window, send pkt
 send ACK(n)
timeout(n):  out-of-order: buffer
 resend pkt n, restart  in-order: deliver (also
timer deliver buffered, in-order
ACK(n) in pkts), advance window to
[sendbase,sendbase+N-1]: next not-yet-received pkt
 mark pkt n as received pkt n in [rcvbase-N,rcvbase-1]
 if n smallest unACKed pkt,
 ACK(n)
advance window base to
next unACKed seq # otherwise:
 ignore

EEEN30024 Lecture 4 12
Selective repeat in
action
sender window (N=4) sender receiver
012345678 send pkt0
012345678 send pkt1
012345678 send pkt2 receive pkt0, send ack0
012345678 send pkt3 Xloss receive pkt1, send ack1
(wait)
receive pkt3, buffer,
012345678 rcv ack0, send pkt4 send ack3
012345678 rcv ack1, send pkt5 receive pkt4, buffer,
send ack4
record ack3 arrived receive pkt5, buffer,
send ack5
pkt 2 timeout
012345678 send pkt2
012345678 record ack4 arrived
012345678 rcv pkt2; deliver pkt2,
record ack5 arrived
012345678 pkt3, pkt4, pkt5; send ack2

EEEN30024 Lecture 4 13

sender window receiver window


(after receipt) (after receipt)

Selective repeat: 0123012 pkt0

dilemma 0123012
0123012
pkt1
pkt2
0123012
0123012
0123012
example: 0123012 pkt3
X
 seq #’s: 0, 1, 2, 3 0123012
pkt0 will accept packet
 window size=3 with seq number 0
(a) no problem
 receiver sees no
difference in two receiver can’t see sender side.
receiver behavior identical in both cases!
scenarios! something’s (very) wrong!
 duplicate data accepted
as new in (b) 0123012 pkt0
pkt1
Note: seq # range must 0123012 0123012
pkt2
be at least twice
0123012 0123012
X 0123012
window size to avoid X
timeout
problem in (b): retransmit pkt0 X
pkt0
window size N <= 2k-1 0123012
will accept packet
with seq number 0
(b) oops!
EEEN30024 Lecture 4 14
Selective Repeat

 Selective Repeat Dilemma:


 limit largest window size to W = 2k-1
• avoids overlaps in the sender’s and receiver’s
windows that would result in duplicate packets being
accepted as "new" data

 See the Selective Repeat protocol applet at :


http://wps.aw.com/aw_kurose_network_5/111/28536/73053
12.cw/index.html

EEEN30024 Lecture 4 15

TCP: Overview
RFCs: 793, 1122, 1323, 2018, 2581
TCP creates a reliable service
on top of IP’s unreliable service
 full duplex data:
 point-to-point:  bi-directional data flow
 one sender, one receiver in same connection
 reliable, in-order byte  MSS: maximum
stream: segment size
 no "message boundaries"  connection-oriented:
 pipelined:  handshaking (exchange
of control msgs)
 TCP congestion and flow
initialises the sender &
control set window size
receiver states, before
 send & receive buffers data exchange
 flow controlled:
 sender will not
overwhelm receiver

EEEN30024 Lecture 4 16
TCP segment structure
32 bits
URG: urgent data counting
(generally not used) source port # dest port #
by bytes
sequence number of data
ACK: ACK #
valid acknowledgement number (not segments!)
head not
PSH: push data now len used
UAP R S F Receive window
(generally not used) # bytes the
checksum Urg data pnter
receiver is
RST, SYN, FIN: Options (variable length) willing
connection estab to accept
(setup, teardown
commands)
application
data
Internet
(variable length)
checksum
(as in UDP)

EEEN30024 Lecture 4 17

TCP seq. #’s and ACKs


Seq. #’s:
 byte stream "number" Host A Host B
of first byte in User
segment’s data types
ACKs: ‘C’
host ACKs
 seq # of next byte receipt of
expected from other ‘C’, echoes
side back ‘C’
 cumulative ACK
Q: how receiver handles host ACKs
out-of-order segments receipt
of echoed
 A: TCP specification ‘C’
doesn’t say, -it is left up
to the implementor
TCP behaves more like time
simple telnet scenario
Selective Repeat than GBN
EEEN30024 Lecture 4 18
TCP Flow Control
flow control
sender won’t overflow
 receive side of TCP receiver’s buffer by
connection has a receive transmitting too much,
buffer: too fast

 speed-matching service:
matching the send rate
to the receiving app’s
drain rate

 app process may be slow


at reading from buffer

EEEN30024 Lecture 4 19

TCP Flow control: how it works

 receiver advertises spare


room by including value
of RcvWindow in segments
("Receive Window" field)
 sender limits unACKed
data to RcvWindow
(suppose TCP receiver discards  guarantees receive
out-of-order segments) buffer doesn’t overflow
 spare room in buffer  see Flow Control applet:
= RcvWindow http://wps.aw.com/aw_kurose_
= RcvBuffer-[LastByteRcvd - network_5/111/28536/7305
LastByteRead] 312.cw/index.html

EEEN30024 Lecture 4 20
TCP Connection Management
Recall: TCP sender, receiver Three way handshake:
establish "connection "
before exchanging data Step 1: client host sends TCP
segments SYN segment to server
 initialize TCP variables:  specifies initial seq #
 seq. #s  no data
 buffers, flow control info Step 2: server host receives
(e.g. RcvWindow) SYN, replies with ACK
segment
 client: connection initiator  server allocates buffers
Socket clientSocket = new  specifies server initial seq.
Socket("hostname","port number"); #
 server: contacted by client Step 3: client receives ACK,
Socket connectionSocket = replies with ACK segment,
welcomeSocket.accept();
which may contain data

EEEN30024 Lecture 4 21

TCP 3-way handshake

client state server state

LISTEN LISTEN
choose init seq num, x
send TCP SYN msg
SYNSENT SYNbit=1, Seq=x
choose init seq num, y
send TCP ACK
msg, acking SYN SYN RCVD
SYNbit=1, Seq=y
ACKbit=1; ACKnum=x+1
received ACK(x)
ESTAB indicates server is live;
send ACK for ACK;
this segment may contain ACKbit=1, ACKnum=y+1
client-to-server data
received ACK(y)
indicates client is live
ESTAB

EEEN30024 Lecture 4 22
TCP Connection Management (cont)

Closing a connection: client server

close
client closes socket:
clientSocket.close();

Step 1: client end system close


sends TCP FIN control
segment to server

timed wait
Step 2: server receives
FIN, replies with ACK.
Closes connection, sends
FIN. closed

EEEN30024 Lecture 4 23

TCP Connection Management (cont)

Step 3: client receives client server


FIN, replies with ACK
closing
 Enters "timed wait" -
will respond with ACK
to received FINs
closing
Step 4: server, receives
ACK. Connection closed.
timed wait

closed
Note: not shown are
the sequence numbers
that accompany the FINs closed
and ACKs
EEEN30024 Lecture 4 24
Principles of Congestion Control

Congestion:
 informally: "too many sources sending too
much data too fast for network to handle"
 different from flow control!
 manifestations:
 lost packets (buffer overflow at routers)
 long delays (queueing in router buffers)
 a major transport layer problem!

EEEN30024 Lecture 4 25

Approaches towards
congestion control
Two broad approaches towards congestion
control:
end-end congestion network-assisted
control: congestion control:
 no explicit feedback from  routers provide feedback
network to end systems
 congestion inferred from  single bit indicating
end-system observed congestion (SNA,
loss, delay DECbit, TCP/IP ECN,
 approach taken by TCP ATM)
 explicit rate sender
should send at

EEEN30024 Lecture 4 26
TCP congestion control:
additive increase, multiplicative decrease

 approach: increase transmission rate (window size),


probing for usable bandwidth, until loss occurs
 additive increase: increase cwnd by 1 MSS every RTT
until loss detected
 multiplicative decrease: cut cwnd in half after loss
cwnd: congestion window size

saw tooth
behavior: probing
for bandwidth

time

EEEN30024 Lecture 4 27

TCP Congestion Control:


details
 sender limits transmission: How does sender
LastByteSent-LastByteAcked perceive congestion?
 cwnd  loss event = timeout
 roughly, or 3 duplicate acks
cwnd  TCP sender reduces
rate = Bytes/sec
RTT rate (cwnd) after loss
 cwnd is dynamic, function of event
perceived network three mechanisms:
congestion  AIMD
 slow start
 conservative after
timeout events
EEEN30024 Lecture 4 28
TCP Slow Start
 when connection Host A Host B
begins, increase rate
exponentially until

RTT
first loss event:
 initially cwnd = 1 MSS
 double cwnd every
RTT
 done by incrementing
cwnd for every ACK
received
 summary: initial rate
is slow but ramps up time
exponentially fast
EEEN30024 Lecture 4 29

Refinement:
inferring loss
 after 3 dup ACKs:
 cwnd is cut in half Philosophy:
 window then grows
linearly 3 dup ACKs indicates
 but after timeout event: network capable of
delivering some
 cwnd instead set to 1
segments
MSS;
 window then grows  timeout indicates a
exponentially "more alarming"
 to a threshold, then congestion scenario
grows linearly

EEEN30024 Lecture 4 30
Refinement
Q: when should the
exponential
increase switch to
linear?
A: when cwnd gets
to 1/2 of its value
before timeout.

Implementation:
 variable ssthresh
 on loss event, ssthresh
is set to 1/2 of cwnd just
before loss event

EEEN30024 Lecture 4 31

Review Questions &


Wireshark Exercises

 To help you get a better understanding of TCP and UDP


try Wireshark Exercises 3 and 4 on Blackboard.

 Try the Review Questions for Lectures 03-04 on


Blackboard.

EEEN30024 Lecture 4 31
Lecture 4: Summary

 principles behind reliable transport


layer services:
 data transfer protocols
 flow control

 TCP:
 segment structure
 reliable data transfer
 flow control
 connection management
 congestion control

EEEN30024 Lecture 4 33

Appendix: (examinable)
TCP Round Trip Time (RTT)
and Timeout
Q: how to set TCP Q: how to estimate RTT?
timeout value?  SampleRTT: measured time
 longer than RTT from segment transmission
 but RTT varies until ACK receipt
 too short: premature  ignore retransmissions
timeout  SampleRTT will vary, want

 unnecessary estimated RTT "smoother"


retransmissions  average several recent
 too long: slow measurements, not just
reaction to segment current SampleRTT
loss

EEEN30024 Lecture 4 34
TCP Round Trip Time
and Timeout

EstimatedRTT = (1- )*EstimatedRTT + *SampleRTT

 Exponential weighted moving average


 influence of past sample decreases exponentially
fast
 typical value:  = 0.125

EEEN30024 Lecture 4 35

Example RTT estimation:

EEEN30024 Lecture 4 36
TCP Round Trip Time and Timeout
Setting the timeout
 EstimatedRTT plus “safety margin”
 large variation in EstimatedRTT -> larger safety margin
 first estimate of how much SampleRTT deviates from
EstimatedRTT:

DevRTT = (1-)*DevRTT +
*|SampleRTT-EstimatedRTT|

(typically,  = 0.25)

Then set timeout interval:

TimeoutInterval = EstimatedRTT + 4*DevRTT

EEEN30024 Lecture 4 37

TCP: retransmissions

 TCP uses cumulative ACKs


 TCP uses a single retransmission timer
 TCP retransmissions are triggered by:
 timeout events
 duplicate ACKs

EEEN30024 Lecture 4 38
TCP: retransmission scenarios
Host A Host B Host A Host B

Seq=92 timeout
timeout

X
loss

SendBase

Seq=92 timeout
= 100
SendBase
= 120

SendBase
= 100 SendBase
= 120
lost ACK scenario premature timeout
time
time
EEEN30024 Lecture 4 39

TCP: fast retransmit


scheme
 time-out period  if sender receives 3
often relatively long: ACKs for the same
 long delay before data, it supposes that
resending lost packet segment after ACKed
 detect lost segments data was lost:
via duplicate ACKs.  fast retransmit: resend
 sender often sends segment before timer
many segments back- expires
to-back
 if segment is lost,
there will likely be
many duplicate ACKs.

EEEN30024 Lecture 4 40
Host A Host B

TCP: fast
retransmit X

timeout

time
Figure 3.37 Resending a segment after triple duplicate ACK
EEEN30024 Lecture 4 41
Lecture 5:
Network Layer (1/3)

Learning Outcomes :

 Understand principles behind network


layer services:
 network layer service models
 forwarding versus routing
 IP Protocol
 DHCP

EEEN30024 Lecture 5 1

Network Layer
 transport segment from application

sending to receiving host transport


network
data link
 on sending side physical
network
network
encapsulates segments network
data link
physical
data link
physical
data link
into datagrams physical network network
data link data link

 on receiving side, physical physical

delivers segments to network


data link
network
data link

transport layer physical


network
data link
physical

network layer protocols


physical
 application
network transport
in every host, router data link
physical
network
network
data link
network data link physical
 router examines header data link
physical
physical

fields in all IP datagrams


passing through it

EEEN30024 Lecture 5 2
Two Key Network-Layer Functions
 forwarding: move analogy:
packets from
router’s input to  routing: process of
appropriate router planning trip from
output source to dest

 routing: determine  forwarding: process


route taken by of getting through
packets from source single interchange
to dest.
 routing algorithms
EEEN30024 Lecture 5 3

Forwarding and Routing

routing algorithm

local forwarding table router table


header value output link
0100 3
0101 2
0111 2
1001 1

value in arriving
packet’s header
0111 1

3 2

EEEN30024 Lecture 5 4
Network Layer Connection
and Connection-less
Services
 datagram network provides network-
layer connection-less service
 e.g. the Internet

 VC (Virtual Circuit) network provides


network-layer connection service
 analogous to the transport-layer services,
but with implementation in the network not
the hosts.
 e.g. ATM, Frame Relay
ATM = Asynchronous Transfer Mode
EEEN30024 Lecture 5 5

Network Layer
Connection Service
Example services provided :

example services for example services for a


individual flow of datagrams:
datagrams:  in-order datagram
 guaranteed delivery delivery
 guaranteed delivery  guaranteed
with less than 40 minimum bandwidth
msec delay to flow
 restrictions on
The Internet offers none of the
above! Instead it is termed a changes in inter-
"best effort" service model. packet spacing
EEEN30024 Lecture 5 6
Virtual Circuits
"source-to-destination path behaves much like
a telephone circuit"
 performance-wise
 network actions along the path

 call setup, teardown for each call before data can flow
 each packet carries VC identifier (not destination host
address) in the header
 every router on the path maintains "state" for each
passing connection
 link, router resources (bandwidth, buffers) may be
allocated to VC (dedicated resources = predictable
service)

EEEN30024 Lecture 5 7

VC Implementation
a VC consists of:
1. path from source to destination
2. VC numbers, one number for each link along
path
3. entries in forwarding tables in routers along
path

 packet belonging to VC carries VC number


(rather than destination address)
 VC number can be changed on each link.
 new VC number comes from forwarding table

EEEN30024 Lecture 5 8
VC number
Router "A"
VC Forwarding 22 32
12
Table 1
2
3

Forwarding table in interface


number
Router "A":
Incoming interface Incoming VC # Outgoing interface Outgoing VC #

1 12 3 22
2 63 1 18
3 7 2 17
1 97 3 87
… … … …

Routers maintain connection state information!

EEEN30024 Lecture 5 9

Virtual Circuits: signaling protocols


 used to setup, maintain teardown VC
 used in ATM, frame-relay, X.25
 not used in today’s Internet

application
5. Data flow begins 6. Receive data application
transport
transport
network 4. Call connected 3. Accept call
network
data link 1. Initiate call
2. incoming call data link
physical
physical

EEEN30024 Lecture 5 10
Datagram Networks
 no call setup at network layer
 routers: no state about end-to-end connections
 no network-level concept of "connection"
 packets forwarded using destination host address
 packets between same source-destination pair may
take different paths

application application
transport transport
network 1. Send data 2. Receive data network
data link data link
physical physical

EEEN30024 Lecture 5 11

Datagram Forwarding Table

routing algorithm millions of IP addresses,


so rather than list
individual destination
local forwarding table
dest address output link addresses list range of
address-range 1 3 addresses
address-range 2
address-range 3
2
2
(aggregate table entries)
address-range 4 1

IP destination address in
arriving packet’s header
1

3 2

EEEN30024 Lecture 5 12
Datagram Forwarding Table
Destination Address Range Link Interface

11001000 00010111 00010000 00000000


through 0
11001000 00010111 00010111 11111111

11001000 00010111 00011000 00000000


through 1
11001000 00010111 00011000 11111111

11001000 00010111 00011001 00000000


through 2
11001000 00010111 00011111 11111111

otherwise 3

EEEN30024 Lecture 5 13

Longest Prefix Matching


Longest prefix matching
when looking for forwarding table entry for given
destination address, use longest address prefix
that matches destination address.

Destination Address Range Link interface


11001000 00010111 00010*** ********* 0
11001000 00010111 00011000 ********* 1
11001000 00010111 00011*** ********* 2
otherwise 3

Examples:
DA: 11001000 00010111 00010110 10100001 to link interface 0
DA: 11001000 00010111 00011000 10101010 to link interface 1

EEEN30024 Lecture 5 14
Datagram or VC Network: why?
Datagram (Internet) VC (ATM)
 data exchange among  evolved from telephony
computers  human conversation:
 "elastic" service, no  strict timing,
strict timing req. reliability
 "smart" end systems requirements
(computers)  need for guaranteed
 can adapt, perform service
control, error recovery  "dumb" end systems
 simple inside network,  telephones
complexity at "edge"
 complexity inside
 many link types network
 different characteristics
 uniform service difficult

EEEN30024 Lecture 5 15

The Internet Network Layer


Host, router network layer functions:

Transport layer: TCP, UDP

Routing protocols IP protocol


•path selection •addressing conventions
•RIP, OSPF, BGP •datagram format
Network •packet handling conventions
layer forwarding
table ICMP protocol
•error reporting
•router "signaling"

Link layer

physical layer

EEEN30024 Lecture 5 16
IP Datagram Format
IP protocol version
number 32 bits total datagram
length (bytes)
header length head type of
(bytes) ver service length
.
for
"type" of data len fragment
16-bit identifier flgs fragmentation/
offset reassembly
max number time to upper header
remaining hops live layer 1s complement
checksum
(decremented at sum of the
each router) 32 bit source IP address header fields
upper layer protocol 32 bit destination IP address
to deliver payload to,
e.g. 4=TCP, 17=UDP Options (if any) E.g. timestamp,
record route
how much overhead data taken, specify
with TCP? (variable length, list of routers
to visit.
 20 bytes of TCP typically a TCP
 20 bytes of IP or UDP segment)
 = 40 bytes + app
layer overhead

EEEN30024 Lecture 5 17

IP Fragmentation
& Reassembly
 network links have MTU
(Max. Transfer Unit size)
-largest possible link-level
frame. fragmentation:
in: one large
 different link types have
datagram
different MTUs out: 3 smaller
 IP datagrams larger than datagrams
MTU are fragmented by
router
reassembly
 one datagram becomes
several datagrams
 "reassembled" only at
final destination host
 IP header bits used to
identify, order related
fragments

EEEN30024 Lecture 5 18
IP Fragmentation and
Reassembly
length ID fragflag offset
=4000 =x =0 =0
Example
 4000 byte
One large datagram becomes
datagram several smaller datagrams
 MTU = 1500
bytes length ID fragflag offset
=1500 =x =1 =0
1480 bytes in
data field length ID fragflag offset
=1500 =x =1 =185
offset =
1480/8 length ID fragflag offset
=1040 =x =0 =370

Applet:
http://wps.aw.com/aw_kurose_network_5/111/28536/7305312.cw/index.html

EEEN30024 Lecture 5 19

IP Addressing: introduction

 IP address: 32-bit 223.1.1.1

identifier for host, 223.1.1.2


223.1.2.1

router interface 223.1.1.4 223.1.2.9


 interface: 223.1.2.2
connection between 223.1.1.3 223.1.3.27

host/router and
physical link
 router’s typically 223.1.3.1 223.1.3.2
have multiple
interfaces
 host typically has
one interface 223.1.1.1 = 11011111 00000001 00000001 00000001
 IP addresses 223 1 1 1
associated with each
interface
EEEN30024 Lecture 5 20
Subnets
223.1.1.1
 IP address: 223.1.2.1
 subnet part (high 223.1.1.2
order bits) 223.1.1.4 223.1.2.9

 host part (low order 223.1.2.2


bits) 223.1.1.3 223.1.3.27

 What is a subnet ? subnet


 device interfaces
with same subnet 223.1.3.1 223.1.3.2

part of IP address
 can physically reach
each other without network consisting of 3 subnets
intervening router

EEEN30024 Lecture 5 21

Subnets 223.1.1.0/24
223.1.2.0/24

Recipe
 to determine the
subnets, detach each
interface from its
host or router,
creating islands of
isolated networks
 each isolated
network is called a 223.1.3.0/24

subnet.
Subnet mask: /24
defines the subnet address

EEEN30024 Lecture 5 22
223.1.1.2

Subnets
223.1.1.1 223.1.1.4

How many?
223.1.1.3

223.1.9.2 223.1.7.0

223.1.9.1 223.1.7.1
223.1.8.1 223.1.8.0

223.1.2.6 223.1.3.27

223.1.2.1 223.1.2.2 223.1.3.1 223.1.3.2

EEEN30024 Lecture 5 23

IP Addressing: CIDR

CIDR: Classless InterDomain Routing


 subnet portion of address of arbitrary length
 address format: a.b.c.d/x, where x is # bits in
subnet portion of address

subnet host
part part
11001000 00010111 00010000 00000000
200.23.16.0/23
often simply referred to as the "network" part of the address

EEEN30024 Lecture 5 24
IP Addresses: how to get one?

Q: How does a host get IP address?

 hard-coded by system admin in a file


 Windows: control-panel->network-
>configuration->tcp/ip->properties
 UNIX: /etc/rc.config

 DHCP: Dynamic Host Configuration Protocol:


dynamically get address from a server
 "plug-and-play"

EEEN30024 Lecture 5 25

DHCP:
Dynamic Host Configuration Protocol

Goal: allow host to dynamically obtain its IP address


from network server when it joins network
-can renew its lease on address in use
-allows reuse of addresses
-support for mobile users who want to join network (more
shortly)
DHCP overview:
 host broadcasts "DHCP discover" msg [optional]
 DHCP server responds with "DHCP offer" msg
[optional]
 host requests IP address: "DHCP request" msg
 DHCP server sends address: "DHCP ack" msg
EEEN30024 Lecture 5 26
DHCP Client-Server Scenario

A 223.1.1.1 DHCP 223.1.2.1


server
223.1.1.2
223.1.1.4 223.1.2.9
B
223.1.2.2 arriving DHCP
223.1.1.3 223.1.3.27 E client needs
address in this
223.1.3.1 223.1.3.2
network

EEEN30024 Lecture 5 27

DHCP Client-Server Scenario


DHCP server: 223.1.2.5 arriving
DHCP discover
client
src : 0.0.0.0, 68
dest.: 255.255.255.255,67
yiaddr: 0.0.0.0
transaction ID: 654

DHCP offer
src: 223.1.2.5, 67
dest: 255.255.255.255, 68
yiaddrr: 223.1.2.4
transaction ID: 654
Lifetime: 3600 secs
DHCP request
src: 0.0.0.0, 68
dest:: 255.255.255.255, 67
yiaddrr: 223.1.2.4
transaction ID: 655
time Lifetime: 3600 secs

DHCP ACK
src: 223.1.2.5, 67
dest: 255.255.255.255, 68
yiaddrr: 223.1.2.4
transaction ID: 655
Lifetime: 3600 secs

EEEN30024 Lecture 5 28
DHCP: more than IP address
DHCP can return more than just allocated
IP address on subnet:
 address of first-hop router for client
 name and IP address of DNS sever
 network mask (indicating network versus
host portion of address)

EEEN30024 Lecture 5 29

DHCP: example
 connecting laptop needs
DHCP DHCP its IP address, addr of
UDP
DHCP
DHCP IP
first-hop router, addr of
DHCP Eth DNS server: use DHCP
Phy
 DHCP request
encapsulated in UDP,
DHCP

encapsulated in IP,
DHCP DHCP encapsulated in 802.1
DHCP UDP 168.1.1.1 Ethernet frame
IP
Ethernet frame broadcast
DHCP

Eth router
(dest: FFFFFFFFFFFF) on
DHCP

Phy (runs DHCP)


LAN, received at router
running DHCP server

 Ethernet demuxed to IP
demuxed, UDP demuxed
to DHCP

EEEN30024 Lecture 5 30
DHCP: example

DHCP DHCP  DCP server formulates


DHCP UDP DHCP ACK containing
DHCP IP client’s IP address, IP
DHCP Eth address of first-hop
Phy router for client, name &
IP address of DNS server

 encapsulation of DHCP
DHCP DHCP server, frame forwarded
DHCP UDP to client, demuxing up
DHCP IP to DHCP at client
DHCP Eth router  client now knows its IP
DHCP
Phy (runs DHCP) address, name and IP
address of DSN server,
IP address of its first-
hop router

EEEN30024 Lecture 5 31

Lecture 5 :
Summary
Introduction
Virtual circuit and
datagram networks
IP: Internet Protocol
 IP Datagram
 Fragmentation/re- Next:
assembly
 IP address allocation
 CIDR
 NAT
 Subnets
 ICMP
 IPv4 addressing
 IPV6
 DHCP

EEEN30024 Lecture 5 32
Lecture 6:
Network Layer (2/3)
Learning Outcomes :

 Further principles behind network layer


services:
 Address subnetting
 NAT
 ICMP
 IPV6
 IP address allocation

EEEN30024 Lecture 6 1

IP address Allocation:
ICANN

ICANN: Internet Corporation for Assigned


Names and Numbers

 global authority
 manages DNS root servers
 assigns domain names, resolves disputes
 allocates addresses to regional Internet
registries, e.g. RIPE (Europe), ARIN (Asia),
etc
• they in turn allocate blocks of addresses to
regional/national ISPs (Nominet in the UK)
ISP = Internet Service Provider

EEEN30024 Lecture 6 2
Hierarchical addressing allows
efficient advertisement of routing
information
Example
ISPs divide up allocated block to individual customers
Customer 0
200.23.16.0
Customer 1
Allocated block:
200.23.18.0 200.23.16.0/20
Customer 2
200.23.20.0 . Fly-By-Night-ISP
.
. .
. National
Customer 7 . registry
200.23.30.0
Allocated block:
ISPs-R-Us
199.31.0.0/16

EEEN30024 Lecture 6 3

IP Address Allocation
The ISP’s customers are allocated a portion of
the address space
ISP's block 11001000 00010111 00010000 00000000 200.23.16.0/20

Customer 0 11001000 00010111 00010000 00000000 200.23.16.0/23


Customer 1 11001000 00010111 00010010 00000000 200.23.18.0/23
Customer 2 11001000 00010111 00010100 00000000 200.23.20.0/23
... ….. …. ….
Customer 7 11001000 00010111 00011110 00000000 200.23.30.0/23
notice subnet mask lengths

In this example the ISP divides its address block into eight
equal-sized address blocks, each of which is allocated to a
customer. Each customer has 32 – 23 = 9 bits of address space
for addressing individual hosts, i.e. 29 = 512 hosts.
Q: is a customer likely to have a single LAN with this many hosts ?

EEEN30024 Lecture 6 4
Address Subnetting

 Individual customers can subnet their own address block.


 Idea is to extend the subnet mask into the host part of the
address
 Suppose a customer has the following address block :
11001000 00010111 00010000 00000000 200.23.16.0/23
Say it wanted to distribute the addresses over 18 networks.
How to do this ?
There are 9 bits available for host addressing
 5 bits could be used for subnet id
• giving 32 subnets
 4 bits for host
• giving 16 hosts (per subnet)
– (actually 14 as there are two special addresses)

EEEN30024 Lecture 6 5

Address Subnetting
 Starting with
11001000 00010111 00010000 00000000 200.23.16.0/23

 subnet 0 : 200.23.16.0/28
host 1: 11001000 00010111 00010000 00000001 200.23.16.1
host 14:11001000 00010111 00010000 00001110 200.23.16.14

 subnet 1 : 200.23.16.16/28
host 1: 11001000 00010111 00010000 00010001 200.23.16.17
host 14:11001000 00010111 00010000 00011110 200.23.16.30

subnet 2 : 200.23.16.32/28
subnet 3 : 200.23.16.48/28
…etc
Host addresses 0 and 15 reserved. Why ?

EEEN30024 Lecture 6 6
Subnet Example
To the outside, this looks like a single network -the subnetting is not visible .
E.g. 200.23.16.44 is routed to subnet 2, but this is unknown to the sender.

200.23.16.0/28 200.23.16.48/28

200.23.16.16/28 200.23.16.64/28

200.23.16.32/28 200.23.16.80/28
.
.
.
. .
. .
. The main router’s tables contains
not all subnets shown in example entries for each subnet
EEEN30024 Lecture 6 7

Subnet Mask
 A router uses a subnet mask to extract all
the bits of an address except the host.

 In the above example 28 bits of


200.23.16.0 were used for the subnet,
thus all but least significant 4 bits are
required
 11111111.11111111.11111111.11110000
 255.255.255.240
 Also written as /28

EEEN30024 Lecture 6 8
How a router uses
the subnet mask
 To determine which subnet to route a packet to,
the subnet mask is ANDed with the address.

 Suppose
 IP address 200.23.16.44
 mask /28
 Gives
11001000.00010111.00001000.00101100 AND
11111111.11111111.11111111.11110000 gives
11001000.00010111.00001000.00100000
- 200.23.16.32
 Thus within this network, subnet 2 is used
• the highlighted bits give the subnet number

EEEN30024 Lecture 6 9

Classful Addressing
 IP addresses were originally used in 5 classes – so
called classful addressing:

 E.g. 197.32.24.11 is a class C address to network number


197.32.24 and host number 11
 Multicast addressing
 packets are sent to a subset of network nodes

EEEN30024 Lecture 6 10
Classful Addressing

 Network portions of IP addresses constrained


according to the scheme above
 8, 16 or 24 bits for unicast addressing

 Scheme became too restrictive


 class B supports 216 -2 = 65534 hosts
 class C supports 28 – 2 = 254 hosts
• for a company typically with 2000 hosts class C is not sufficient but
class B is wasteful
 classes B and C depleted rapidly with growth on the Internet
• ‘rescued’ by widespread use of private IP addressing

EEEN30024 Lecture 6 11

Private IP Addresses
 Within class A, B and C networks there are defined ranges
of private addresses (using CIDR notation –see later):
 class A: 10.0.0.0/8
 class B: 172.16.0.0/12
 class C: 192.168.0.0/16

 Private IP addresses are used in private networks


 not connected directly to the Internet, instead use e.g.
Network Address Translation (NAT)
 routers are normally configured to discard traffic with such
addresses

 Strong motivations for their use are


 shortage, and cost, of publically registered addresses
 security, as it is not possible to establish a direct connection to
a host using a private address
 multiple networks can use the same private address range
without risk of address conflicts.

EEEN30024 Lecture 6 12
NAT:
Network Address Translation
rest of local network
Internet (e.g., home network)
10.0.0/8 10.0.0.1

10.0.0.4
10.0.0.2
138.76.29.7

10.0.0.3

All datagrams leaving local Datagrams with source or


network have same single source destination in this network
NAT IP address: 138.76.29.7, have 10.0.0/8 address for
different source port numbers source, destination (as usual)

EEEN30024 Lecture 6 13

NAT:
Network Address Translation
 Motivation: local network uses just one IP address
as far as outside world is concerned:
 range of addresses not needed from ISP: just
one IP address for all devices
 can change addresses of devices in local network
without notifying outside world
 can change ISP without changing addresses of
devices in local network
 devices inside local net not explicitly
addressable, visible by outside world (a security
plus).

EEEN30024 Lecture 6 14
NAT:
Network Address Translation
Implementation: NAT router must:
 outgoing datagrams: replace (source IP address, port #) of
every outgoing datagram to (NAT IP address, new port #)
. . . remote clients/servers will respond using (NAT IP
address, new port #) as destination addr.

 remember (in NAT translation table) every (source IP


address, port #) to (NAT IP address, new port #)
translation pair

 incoming datagrams: replace (NAT IP address, new port #)


in dest fields of every incoming datagram with
corresponding (source IP address, port #) stored in NAT
table

EEEN30024 Lecture 6 15

NAT:
Network Address Translation
NAT translation table 1: host 10.0.0.1
2: NAT router WAN side addr LAN side addr sends datagram to
changes datagram
138.76.29.7, 5001 10.0.0.1, 3345 128.119.40.186, 80
source addr from
10.0.0.1, 3345 to …… ……
138.76.29.7, 5001,
updates table S: 10.0.0.1, 3345
D: 128.119.40.186, 80
10.0.0.1
1
S: 138.76.29.7, 5001
2 D: 128.119.40.186, 80 10.0.0.4
10.0.0.2

138.76.29.7 S: 128.119.40.186, 80
D: 10.0.0.1, 3345 4
S: 128.119.40.186, 80
D: 138.76.29.7, 5001 3 10.0.0.3
4: NAT router
changes datagram
3: Reply arrives dest addr from
dest. address: 138.76.29.7, 5001 to 10.0.0.1, 3345
138.76.29.7, 5001

EEEN30024 Lecture 6 16
NAT:
Network Address Translation
 16-bit port-number field:
 60,000 simultaneous connections with a
single LAN-side address!
 NAT is controversial:
 routers should only process up to layer 3
 violates end-to-end argument
• NAT possibility must be taken into
account by app designers, e.g., P2P
applications
 address shortage should instead be solved
by IPv6

EEEN30024 Lecture 6 17

NAT traversal problem


 client wants to connect to
server with address 10.0.0.1
 server address 10.0.0.1 10.0.0.1
local to LAN (client can’t Client
use it as destination addr) ?
 only one externally visible 10.0.0.4
NATed address:
138.76.29.7 138.76.29.7 NAT
router
 solution 1: statically configure
NAT to forward incoming
connection requests at given
port to server
 e.g., (123.76.29.7, port
2500) always forwarded to
10.0.0.1 port 25000

EEEN30024 Lecture 6 18
NAT traversal problem

 solution 2: Universal Plug


and Play (UPnP) Internet 10.0.0.1
Gateway Device (IGD)
Protocol. Allows NATed host IGD
to: 10.0.0.4
learn public IP address
138.76.29.7 NAT
(138.76.29.7) router
add/remove port
mappings (with lease
times)

i.e., automate static NAT


port map configuration

EEEN30024 Lecture 6 19

NAT traversal problem


 solution 3: relaying (used in Skype)
 NATed client establishes connection to relay
 External client connects to relay
 relay bridges packets between to connections

2. connection to
relay initiated 1. connection to
by client relay initiated
by NATed host 10.0.0.1
3. relaying
Client
established
138.76.29.7 NAT
router

EEEN30024 Lecture 6 20
ICMP:
Internet Control Message Protocol
 used by hosts & routers to
communicate network-level
information Type Code description
0 0 echo reply (ping)
 error reporting:
3 0 dest. network unreachable
unreachable host,
3 1 dest host unreachable
network, port, protocol
3 2 dest protocol unreachable
 echo request/reply 3 3 dest port unreachable
(used by ping) 3 6 dest network unknown
 network-layer "above" IP: 3 7 dest host unknown
 ICMP msgs carried in IP 4 0 source quench (congestion
datagrams control - not used)
 ICMP message: type, code 8 0 echo request (ping)
plus first 8 bytes of IP 9 0 route advertisement
datagram causing error 10 0 router discovery
11 0 TTL expired
 ‘ping’ program sends ICMP
12 0 bad IP header
type 8 code 0 to a host
 destination host replies with a
type 0 code 0 ICMP reply
EEEN30024 Lecture 6 21

Traceroute and ICMP

 Source sends series of UDP  when ICMP message


segments to dest arrives, source calculates
 first has TTL =1 RTT
 second has TTL=2, etc.  traceroute does this 3 times
 unlikely port number
 TTL field decremented by Stopping criterion
one by each router
 UDP segment eventually
 When nth datagram arrives arrives at destination host
to nth router:
 destination returns ICMP
 router discards datagram
"port unreachable“ packet
 and sends to source an
(type 3, code 3)
ICMP message (type 11,
code 0)  when source gets this ICMP,
 ICMP message includes stops.
name of router & IP
address

EEEN30024 Lecture 6 22
IPv6

 Initial motivation: 32-bit address space


soon to be completely allocated.
 Additional motivation:
 header format helps speed
processing/forwarding
 header changes to facilitate QoS
IPv6 datagram format:
 fixed-length 40 byte header
 no fragmentation allowed

EEEN30024 Lecture 6 23

IPv6 Header (Cont)


Priority: identify priority among datagrams in flow
Flow Label: identify datagrams in same "flow"
(concept of "flow" not well defined).
Next header: identify upper layer protocol for data

ver pri flow label


payload len next hdr hop limit
source address
(128 bits)
destination address
(128 bits)

data

32 bits

EEEN30024 Lecture 6 24
Other Changes from IPv4

 Checksum: removed entirely to reduce


processing time at each hop
 Options: allowed, but outside of header,
indicated by "Next Header" field
 ICMPv6: new version of ICMP
 additional message types, e.g. "Packet Too
Big"
 multicast group management functions

EEEN30024 Lecture 6 25

Transition From IPv4 To IPv6

 Not all routers can be upgraded


simultaneous
 no "flag days"
 How will the network operate with mixed IPv4
and IPv6 routers?
 Tunneling: IPv6 carried as payload in IPv4
datagram among IPv4 routers

EEEN30024 Lecture 6 26
Tunneling

A B E F
Logical view: tunnel

IPv6 IPv6 IPv6 IPv6

A B E F
Physical view:
IPv6 IPv6 IPv4 IPv4 IPv6 IPv6

EEEN30024 Lecture 6 27

Tunneling
A B E F
Logical view: tunnel

IPv6 IPv6 IPv6 IPv6

A B C D E F
Physical view:
IPv6 IPv6 IPv4 IPv4 IPv6 IPv6

Flow: X Src:B Src:B Flow: X


Src: A Dest: E Dest: E Src: A
Dest: F Dest: F
Flow: X Flow: X
Src: A Src: A
data Dest: F Dest: F data

data data

A-to-B: E-to-F:
B-to-C: B-to-C:
IPv6 IPv6
IPv6 inside IPv6 inside
IPv4 IPv4

EEEN30024 Lecture 6 28
Lecture 6 : summary

 Further principles
behind network
layer services:
 IP address Next:Routing
allocation algorithms
 Link state
 Subnetting
 Distance Vector
 NAT  Hierarchical routing
 ICMP
 IPV6

EEEN30024 Lecture 6 29
Lecture 7:
Network Layer (3/3)

Learning Outcomes :

Routing algorithms
 Link State
 Distance Vector

Reading: K&R section 4.5

EEEN30024 Lecture 7 1

Routing
Context for lecture

 Network layer determines path taken by packets


through the network : routing
 find the "best" path from source to destination

packet

EEEN30024 Lecture 7 2
Forwarding and Routing

routing algorithm

local forwarding table router table


header value output link (simplified)
0100 3 • each link has a
0101 2
0111 2 notional ‘cost’
1001 1

value in arriving
packet’s header
0111 1

3 2

EEEN30024 Lecture 7 3

Routing Algorithm
classification
Global or decentralized Static or dynamic?
information? Static:
Global:
 routes change slowly
 all routers have complete
topology, link cost info
over time
 "link state" algorithms Dynamic:
Decentralized:  routes change more
 router knows physically- quickly
connected neighbors, link
 periodic update
costs to neighbors
 iterative process of  in response to link
computation, exchange of cost changes
info with neighbors
 "distance vector"
algorithms
EEEN30024 Lecture 7 4
Link Cost
 Cost of a link
- path between a pair of of hops – i.e.
number of routers to be traversed
 physical distance
 delay
• queue size for link
• actual delay – use echo packets
 throughput of the link
• high performance links being ‘cheaper’
than low performance links
 monetary cost

EEEN30024 Lecture 7 5

Static Routing
 Permanent routes established based on the
least cost paths
 where cost might be based on hop count,
distance, link performance, etc
 Firstly, get network with costs
 Construct a table for network that gives
the least cost (‘shortest’) path between
each pair of nodes
 Determination of shortest path is given by using
algorithm’s like Dijkstra’s algorithm or the
Bellman-Ford algorithm
• both are considered in this lecture

EEEN30024 Lecture 7 6
from

Static Routing A B C D E F G H
Example
A - A A C B D D G
Central Routing B B - B B B E D F
Table
to C C C - C F D D G
4 E 2
D C D D - F D D G
9 E B E D F - E D F
7 B F 8
F C E D F F - D F
8
A 8 2 H G C D D G F D - G
9
C 1 D 5 H C E D G F H H -
4
G

link
costs
EEEN30024 Lecture 7 7

Static Routing Example

Individual Routing Tables :

A B C D E F G H
D Next D Next D Next D Next D Next D Next D Next D Next
A - A A A A A C A B A D A D A G
B B B - B B B B B B B E B D B F
C C C C C - C C C F C D C D C G
D C D D D D D - D F D D D D D G
E B E E E D E F E - E E E D E F
F C F E F D F F F F F - F D F F
G C G D G D G G G F G D G - G G
H C H E H D H G H F H H H H H -

EEEN30024 Lecture 7 8
Dynamic Routing:
Dijkstra’s algorithm
 A Link State algorithm

 Using the example of finding the least cost paths


associated with router A

4 E 2
9
7 B F 8
8
A 8 2 H
9
C 1
D 5
4
G 9
EEEN30024 Lecture 7

Dijkstra’s algorithm
 Net topology, link costs known to all nodes
 accomplished via "link state broadcast"
 all nodes have same info.
 Computes least cost paths from one node
(‘source’) to all other nodes
 gives forwarding table for that node.

4 E 2
9
7 B F 8
8
A 8 2 H
9
C 1 D 5
4
G

EEEN30024 Lecture 7 10
Dijkstra’s algorithm
 The algorithm uses the following notation
 (Cost, Previous Node) e.g. (7,A) assigned to a node is a
cost of 7 and an indication that the cost associated with
the route is from the neighbour A

 Initially label all nodes (except


(∞,-)
the one whose routing table
is being constructed) with 4 E 2 (∞,-)
(∞,-)
(,-) to indicate that 9
the route is of infinite 7 B F 8 (∞,-)
cost i.e. there is no route 8
A 8 2 H
9
C 1 D 5
(∞,-) (∞,-) 4 G
(∞,-)
EEEN30024 Lecture 7 11

Dijkstra’s algorithm
 Mark the node that is being considered as a
permanent node
 a permanent node is shown unshaded
 Mark its neighbours with the cost of the route
to that node (∞,-)

4 E 2 (∞,-)
(7,A)
9
7 B F 8 (∞,-)
8
A 8 2 H
9
C D 5
1 4
(9,A) (∞,-) G
(∞,-)
12
EEEN30024 Lecture 7
Dijkstra’s algorithm
 From the set of nodes that are not permanent, choose the node
with the lowest cost and make this a permanent node
 in this case B.
 From the set of nodes connected to this new permanent node
examine all neighbouring nodes
 if they are marked permanent, don’t consider further (e.g.. A
in the example)
 if not permanent, compute a cost, based on the cost
associated with the node and the link cost to the
neighbouring node
• if the computed cost is less than the cost associated with
the neighbouring node, update the information at the
neighbour – using the computed cost and the identify of
the permanent node
– e.g. when considering B update information for D, E
and F
• if the computed cost is greater than or equal to the cost at
the neighbouring node, leave neighbouring node
unchanged
 Repeat until all nodes are permanent

EEEN30024 Lecture 7 13

Dijkstra’s algorithm

(11,B)

4 E 2 (16,B)
(7,A)
9
7 B F 8 (∞,-)
8
A 8 2 H
9
C D 5
1 4
(9,A) (15,B) G
(∞,-)

EEEN30024 Lecture 7 14
Dijkstra’s algorithm

(11,B)

4 E 2 (16,B)
(7,A)
9
7 B F 8 (∞,-)
8
A 8 2 H
9
C D 5
1 4
(9,A) (10,C) G
(∞,-)

EEEN30024 Lecture 7 15

Dijkstra’s algorithm

(11,B)

4 E 2 (12,D)
(7,A)
9
7 B F 8 (∞,-)
8
A 8 2 H
9
C D 5
1 4
(9,A) (10,C) G
(14,D)

EEEN30024 Lecture 7 16
Dijkstra’s algorithm

(11,B)

4 E 2 (12,D)
(7,A)
9
7 B F 8 (∞,-)
8
A 8 2 H
9
C D 5
1 4
(9,A) (10,C) G
(14,D)

EEEN30024 Lecture 7 17

Dijkstra’s algorithm

(11,B)

4 E 2 (12,D)
(7,A)
9
7 B F 8 (20,F)
8
A 8 2 H
9
C D 5
1 4
(9,A) (10,C) G
(14,D)

EEEN30024 Lecture 7 18
Dijkstra’s algorithm

(11,B)

4 E 2 (12,D)
(7,A)
9
7 B F 8 (19,G)
8
A 8 2 H
9
C D 5
1 4
(9,A) (10,C) G
(14,D)

EEEN30024 Lecture 7 19

Dijkstra’s algorithm A
D Next
 The routing tables A -
can now be
developed for A by B B
following the paths C C
D C
E B
F C
 The procedure is G C
repeated for each
router. H C
EEEN30024 Lecture 7 20
Dijkstra’s algorithm, discussion
Algorithm complexity: n nodes
 each iteration: need to check all nodes
 n(n+1)/2 comparisons: O(n2)
 more efficient implementations possible: O(nlog2n)
Oscillations possible:
 e.g., link cost = amount of carried traffic

1 A 1+e A A A
2+e 0 0 2+e 2+e 0
D 0 0 B D 1+e 1 B D B D B
0 0 1+e 1
0 e 0 0 1 1+e 0 e
1
C C C C
1
e
… recompute … recompute … recompute
initially
routing
EEEN30024 Lecture 7 21

Link State Routing


 Used at the basis of OSPF widely used
for routing in Internet.

 5 stages to the algorithm


 discover neighbours
 measure cost to neighbours
 construct a packet
• to inform subnet of what it has learnt
 send the packet
 compute shortest path to each router in the
subnet –e.g. using Dijkstra’s algorithm.

EEEN30024 Lecture 7 22
Discover neighbours
 On booting up, send a HELLO packet to
neighbours, neighbours respond by giving
back their network address
 we’ll simply use a single character id to simplify the
issue here
4 E 2
9
7 B F 8
8
A 8 2 H
9
C D 5
1 4
G
23
EEEN30024 Lecture 7

Measure Line Cost


 Estimate delay to neighbours:
 send an ECHO packet to neighbours
 neighbours will respond by returning the packet
 the RTT can be calculated

4 E 2
9
7 B F 8
8
A 8 2 H
9
C D 5
1 4
G
24
EEEN30024 Lecture 7
Build Link State Packets
 Packets can be 4 E 2
constructed at each 9
7 B F 8
router that indicate
the delays to its 8
A 8 2 H
neighbours, e.g..
9
C 1 D 5
4
G
A B C D E F G H
Seq. Seq. Seq. Seq. Seq. Seq. Seq. Seq.
Age Age Age Age Age Age Age Age
B 7 A 7 A 9 B 8 B 4 B 9 D 4 F 8
C 9 C 8 B 8 C 1 F 2 D 2 H 5 G 5
D 8 D 1 F 2 E 2
E 4 G 4 H 8
F 9

25
EEEN30024 Lecture 7

Distributing Link State Packets


 Packets are distributed by a flooding technique.

 To prevent unconstrained flooding each packet


has a sequence number, which is incremented
each time a link state packet is initiated by a
router.

 Routers keep a record of the sequence number of


the link state packets they have received from
each router
 new link state packets are forwarded
 link state packets with sequence numbers that
have already been seen are discarded
EEEN30024 Lecture 7 26
Distributing Link State Packets
 Potential problems
 finite sequence numbers will restart at zero, use a
32-bit number
• 1 packet a second gives a lifetime of 137 years!
 router crashes and restarts at 0
 corruption to sequence number can cause errors

 Solution
 Assign an age to the packet as well a sequence
number
 Decrement the age once per second until it has
reached zero when the information associated with
that packet is discarded
• age is also decremented by each router as the
packet passes through
EEEN30024 Lecture 7 27

Computing New Routes

 A router has information from all other routers


(not just neighbours) and therefore can create
a graph for the subnet.

 Link state algorithm can be run to compute


the least cost (shortest) path for each router
and routing tables can be created.

EEEN30024 Lecture 7 28
Distance Vector Routing
 Distance vector routing is a dynamic technique
that will respond to changes.
 A router has a routing table with
 a row for each router in the network
 in each row it has two entries
• the preferred port over which to reach the router
• the cost of doing so
– number of hops, time delay, queue length
etc…
 A router periodically sends its table to its
neighbours and receives copies of its
neighbour’s tables.
 Using this information and knowing the cost to
its neighbours the router can update its table.

EEEN30024 Lecture 7 29

Distance Vector Routing


-Example

4 E 2
9
7 B F 8
8
A 8 2 H
9
C D 5
1 4
G

Consider information arriving at D from routers B, C, F


and G

EEEN30024 Lecture 7 30
Entry obtained by summing, the cost from D
to the router and selecting the lowest value.
Update Table for D Note: B could be routed via B or F

Table From Table Entries


B C F G for D
to A 7 9 12 14 10 C
B 0 8 6 12 8 B (or F)
C 8 0 3 5 1 C
D 8 1 2 4 0 -
E 4 5 2 8 4 F
F 6 3 0 6 2 F
G 12 5 6 0 4 G
H 14 10 8 5 9 G
D to B = 8 D to C = 1 D to F = 2 D to G = 4 31

Distance Vector
Routing
4 E 2
 Good news travels fast. 9
7 B F 8
 Consider the
8
addition of Router I A 8 2 H
connected to Router G 9
with a cost of 3. C 1 D 5
4
G
 The addition of the new router
and its cost are established after
3 I
3 message exchanges after G has established
cost to I
 1. G’s new table propagated to D and H.
 2. D’s new table propagated to B, C, and F, H’s to F.
 3. A is informed of I by B and C, E is informed of I
by F and B.
32
EEEN30024 Lecture 7
Distance Vector
Routing
4 E 2
 What happens if a link
9
goes down? 7 B F 8
 Suppose the link to I is 8
now removed. A 8 2 H
G advertises cost to I as  9
 C 1 D 5
4
and receives messages from D G
and H advertising the cost as 7 and 8 respectively, I
G updates its table to reflect the cost from D, i.e. a cost of 11.
 Focussing on D and G
 D updates its cost to I to be 15 (message from G)
 G updates its cost to I to be 19 (message from D)
 D updates its cost to I to be 23 (message from G)
• a slow count to infinity!
 "Bad news travels slowly."
EEEN30024 Lecture 7 33

Count to Infinity Problem


 Distance vector routing can suffer from a
count to infinity problem
 bad news travelling slowly.
 Can mitigate the problem to a certain extent
by agreeing on what value is taken to be
infinity.
 When cost is based on hop counts this can be
the maximum hop count + 1, other costs
require other values to be selected.
 Potentially there is still a slow count to a
maximum value.

EEEN30024 Lecture 7 34
Comparison of LS and DV
algorithms
Message complexity Robustness: what happens if
 LS: with n nodes, E links, router malfunctions?
O(nE) msgs sent LS:
 DV: exchange between  node can advertise
neighbors only incorrect link cost
 convergence time varies  each node computes only
its own table
Speed of Convergence
 LS: O(n2) algorithm requires
DV:
O(nE) msgs  DV node can advertise
 may have oscillations incorrect path cost
 DV: convergence time varies  each node’s table used by
others
 may be routing loops
• error propagates
 count-to-infinity problem through network

EEEN30024 Lecture 7 35

Common Router Protocols

 also known as Interior Gateway Protocols (IGP)

 RIP: Routing Information Protocol


• distance vector algorithm
 OSPF: Open Shortest Path First
• Link State algorithm

 Proprietary
• e.g. IGRP: Interior Gateway Routing Protocol (Cisco)

EEEN30024 Lecture 7 36
Lecture 7: Summary

Routing
algorithms
 Link state
 Distance
Vector

EEEN30024 Lecture 7 37
Lecture 8:
Data Link Layer (1/3)

Learning Outcomes :

 Be able to explain the principles


behind :

 data link layer services


 sharing a broadcast channel: multiple
access
 MAC protocols

Reading: K&R section 5.1 – 5.3


EEEN30024 Lecture 8 1

Introduction
Terminology:
 hosts and routers are nodes
 communication channels
that connect adjacent nodes
along communication path
are links
 wired links
 wireless links
 LANs
 layer-2 packet is a frame,
encapsulates datagram

data-link layer has responsibility of


transferring datagram from one node
to physically adjacent node over a link
EEEN30024 Lecture 8 2
Context
transportation analogy
 datagram transferred  trip from London to
by different link Manchester
protocols over different  taxi: London city centre to
links: Heathrow airport
 plane: Heathrow to
 e.g., Ethernet on first
Manchester airport
link, ATM on
intermediate links,  train: airport to Manchester
802.11 on last link city centre
 tourist = datagram
 each link protocol
 transportation =
provides different
communication link
services
 transportation mode = link
 e.g., may or may not layer protocol
provide reliable data
 travel agent = routing
transfer over link
algorithm

EEEN30024 Lecture 8 3

Link Layer Services


Link layer protocols usually provide one or more
of the following services :
 framing, link access:
 encapsulate datagram into frame, adding header,
trailer
 channel access if shared medium
 Medium Access Control ("MAC") addresses used in
frame headers to identify source, destination
• different from IP address
 reliable delivery between adjacent nodes
 saw this already in the transport layer
 seldom used on low bit-error links (e.g. fibre, some
twisted pair)
 wireless links: high error rates
• Q: why both link-level and end-end reliability?
EEEN30024 Lecture 8 4
Link Layer Services
(more)
 flow control:
 pacing between adjacent sending and receiving
nodes
 error detection:
 errors caused by signal attenuation, noise.
 receiver detects presence of errors:
• signals sender for retransmission or drops frame
 error correction:
 receiver identifies and corrects bit error(s) without
resorting to retransmission
 half-duplex and full-duplex
 with half duplex, nodes at both ends of link can
transmit, but not at same time

EEEN30024 Lecture 8 5

Where is the link layer implemented?


 link layer implemented
in host "adaptor" (aka host schematic

network interface card application


NIC) transport
network cpu memory
 Ethernet card, PCMCI link

card, 802.11 card


host
 maybe built-in controller
bus
(e.g., PCI)
 implements link, physical link
physical
layer
physical
transmission

 attaches into host’s


system bus network adapter
card

 combination of
hardware, software,
firmware
EEEN30024 Lecture 8 6
Adaptors Communicating

datagram datagram

controller controller

sending host receiving host


datagram

frame

 sending side:  receiving side


 encapsulates datagram  looks for errors, perform
in frame flow control, etc
 adds error checking  extracts datagram,
bits, flow control, etc. passes to upper layer at
receiving side
EEEN30024 Lecture 8 7

Error Detection
EDC= Error Detection and Correction bits (redundancy)
D = Data protected by error checking, may include header
fields

• Error detection not 100% reliable!


• protocol may miss some errors, hopefully rarely
• larger EDC field yields better detection and correction

otherwise

EEEN30024 Lecture 8 8
Error Checking
Single Bit Parity:
Detect single bit errors

Two Dimensional Bit Parity:


Detect single bit errors in blocks of data

Internet Checksum
Detect multiple bit errors in packets

CRC: Cyclical Redundancy Check


Detect multiple bit errors in packets

-more later

EEEN30024 Lecture 8 9

Multiple Access
Links and Protocols
Two types of "links":
 point-to-point, e.g.
 PPP for old-style Internet dial-up access
 point-to-point link between Ethernet switch and host
 broadcast (shared wire or medium), e.g.
 old-fashioned Ethernet
 802.11 wireless LAN

humans at a
shared wire (e.g., shared RF shared RF cocktail party
cabled Ethernet) (e.g., 802.11 WiFi) (satellite) (shared air, acoustical)

EEEN30024 Lecture 8 10
Multiple Access
protocols
 single shared broadcast channel
 two or more simultaneous transmissions by
nodes: interference
 collision if node receives two or more signals at the same
time

multiple access protocol :


 distributed algorithm that determines how nodes
share channel, i.e., determine when node can
transmit
 communication about channel sharing must use
channel itself
 no out-of-band channel for coordination/control

EEEN30024 Lecture 8 11

Ideal Multiple Access Protocol


Broadcast channel of rate R bps
1. when one node wants to transmit, it can send
at rate R.
2. when M nodes want to transmit, each can
send at average rate R/M
3. fully decentralized:
 no special node to coordinate transmissions
 no synchronization of clocks, slots
4. simple in principle and (hopefully) inexpensive
to implement

EEEN30024 Lecture 8 12
MAC Protocols: a taxonomy

Three broad classes:


 Channel Partitioning
 divide channel into smaller "pieces" (time slots,
frequency, code)
 allocate piece to node for exclusive use
 Random Access
 channel not divided, allow collisions
 "recover" from collisions
 "Taking turns"
 nodes take turns, but nodes with more to send can
take longer turns

EEEN30024 Lecture 8 13

Channel Partitioning MAC


protocols: TDMA
TDMA: time division multiple access
 access to channel in "rounds"
 each station gets fixed length slot (length =
packet transmission time) in each round
 unused slots go idle
 example: 6-station LAN, slots 1,3,4 have
packets, but slots 2,5,6 idle
6-slot
frame
1 3 4 1 3 4

EEEN30024 Lecture 8 14
Channel Partitioning MAC
protocols: FDMA
FDMA: frequency division multiple access
 channel spectrum divided into frequency bands
 each station assigned fixed frequency band
 unused transmission time in frequency bands go idle
 example: 6-station LAN, 1,3,4 have packets, but
frequency bands 2,5,6 idle

frequency bands

FDM cable

EEEN30024 Lecture 8 15

Random Access Protocols


 When node has packet to send
 transmit at full channel data rate R.
 no a priori coordination among nodes
 two or more transmitting nodes ➜ "collision",
 random access MAC protocol specifies:
 how to detect collisions
 how to recover from collisions (e.g., via delayed
retransmissions)
 Examples of random access MAC protocols:
 slotted ALOHA
 ALOHA
 CSMA, CSMA/CD, CSMA/CA

EEEN30024 Lecture 8 16
Slotted ALOHA
Assumptions: Operation:
 all frames same size  when node obtains fresh
 time divided into frame, transmits in next
equal size slots (time slot
to transmit 1 frame)  if no collision: node
 nodes start to can send new frame
transmit only slot in next slot
beginning  if collision: node
 nodes are retransmits frame in
synchronized each subsequent slot
 if 2 or more nodes
with probability p
transmit in slot, all until success
nodes detect collision
EEEN30024 Lecture 8 17

Slotted ALOHA

Pros Cons
 single active node can  collisions, wasting slots
continuously transmit at  idle slots
full rate of channel  nodes may be able to
 highly decentralized: detect collision in less
only slots in nodes need than time to transmit
packet
to be in sync
 clocks have to be
 simple synchronized

EEEN30024 Lecture 8 18
Slotted Aloha efficiency
Efficiency : long-run
fraction of successful  max efficiency: find p*
that maximizes
slots Np(1-p)N-1
(many nodes, all with  for many nodes, take
many frames to send) limit of Np*(1-p*)N-1 as
 suppose: N nodes with N goes to infinity, gives:
many frames to send, each Max efficiency = 1/e = 0.37
transmits in slot with
probability p
 probability that given node
has success in a slot = At best: channel
p(1-p)N-1 used for useful
 prob that any node has a transmissions 37%
success = Np(1-p)N-1 of time!
 result from application of
Poisson distribution
EEEN30024 Lecture 8 19

Pure (unslotted) ALOHA


 unslotted Aloha: simpler, no synchronization
 when frame first arrives
 transmit immediately
 collision probability increases:
 frame sent at t0 collides with other frames sent in [t0-
1,t0+1]
Efficiency: 0.18
Even worse than
slotted ALOHA !

EEEN30024 Lecture 8 20
CSMA (Carrier Sense Multiple Access)

CSMA: listen before transmit:

 if channel sensed idle: transmit entire frame


 if channel sensed busy, defer transmission

 human analogy: don’t interrupt others!

EEEN30024 Lecture 8 21

CSMA spatial layout of nodes

collisions
collisions can still
occur:
propagation delay means
two nodes may not hear
each other’s transmission
collision:
entire packet transmission
time wasted

note:
role of distance & propagation
delay in determining collision
probability
EEEN30024 Lecture 8 22
CSMA/CD (Collision Detection)
CSMA/CD:
 carrier sensing, deferral as in CSMA
 collisions detected within short time
 colliding transmissions aborted, reducing channel
wastage
 collision detection:
 easy in wired LANs: measure signal strengths, compare
transmitted, received signals
• example Ethernet
 difficult in wireless LANs: received signal strength
overwhelmed by local transmission strength
 human analogy: the polite conversationalist

EEEN30024 Lecture 8 23

CSMA/CD collision detection

EEEN30024 Lecture 8 24
"Taking Turns" MAC protocols
channel partitioning MAC protocols:
 share channel efficiently and fairly at high
load
 inefficient at low load: delay in channel
access, 1/N bandwidth allocated even if
only 1 active node!
random access MAC protocols
 efficient at low load: single node can fully
utilize channel
 high load: collision overhead
"taking turns" protocols
look for best of both worlds!
EEEN30024 Lecture 8 25

"Taking Turns" MAC protocols


Polling:
 master node "invites"
slave nodes to data
poll
transmit in turn
 typically used with master
"dumb" slave devices data

 concerns:
 polling overhead
 latency slaves
 single point of failure
(master)

EEEN30024 Lecture 8 26
"Taking Turns" MAC protocols
T
Token passing:
 control token
passed from one
(nothing
node to next to send)
sequentially. T
 token message
 concerns:
 token overhead
 latency
 single point of failure
(token) data

EEEN30024 Lecture 8 27

Summary of MAC protocols

 channel partitioning, by time, frequency or


code
 Time Division, Frequency Division
 random access (dynamic),
 ALOHA, S-ALOHA, CSMA, CSMA/CD
 carrier sensing: easy in some technologies (wire),
hard in others (wireless)
 CSMA/CD used in Ethernet
 CSMA/CA used in 802.11
 taking turns
 polling from central site, token passing
 Bluetooth, FDDI, IBM Token Ring
EEEN30024 Lecture 8 28
IEEE 802 "Reference Model"
 an IEEE standard
 specification of a family of standards for LANs and
MANs (Metropolitan Area Networks)
 deals with two lowest levels of protocol stack
 physical – specifies encoding and decoding
signals, methods of synchronisation, bit
transmission and reception
 data link – split into two sub-layers
• Logical Link Control (LLC)
• Medium Access Control (MAC)
 based on an early standard data link protocol
called HLDC ("High-Level Data Link Control")
 some protocols based on HLDC –e.g. PPP and
X.25
EEEN30024 Lecture 8 29

IEEE 802
LLC and MAC

 LLC sub-layer
 provides an interface to high level protocol (network layer)
– multiplexing and demultiplexing higher level protocols
over the LAN
 optionally manages flow and error control
 e.g. transport layer-style connection-oriented,
acknowledged/unacknowledged connection services

 MAC sub-layer
 assembles frames for transmission with address and error-
detection fields
 disassembles frames on reception performing address
recognition and error detection
 manages access to the shared transmission medium
• the major task of MAC
EEEN30024 Lecture 8 30
IEEE 802 – LLC and MAC
 Why two layers?
 LLC is independent of network, and will
work with a number of different
implementations of the MAC layer
• LLC (IEEE 802.2) can be used with IEEE 802.3
(Ethernet), IEEE 802.5 (Token Ring), IEEE 802.11
(Wireless LAN)

 the MAC layer provides operations (specific


to type of network) concerned with access
to the shared medium
• the LLC header forms part of the payload of an
802 MAC frame and is then transmitted by the
MAC layer

EEEN30024 Lecture 8 31

Lecture 8 Summary

Data Link Layer 1/3

 link layer services


 sharing a broadcast
channel: multiple access
 MAC protocols

EEEN30024 Lecture 8 32
Lecture 9:
Data Link Layer (2/3)
Learning Outcomes :
 Be able to explain error correction and error
detection and be able to use the following
with arbitrary data
 Parity Checking (1D, 2D)
 Hamming Code
 CRC
 Internet Checksum
• 1’s complement of 1’s complement
sum of words
Reading: Stallings "Data and Computer Communications",
Chapter 6, sections 6.2 – 6.4
EEEN30024 Lecture 9 1

Introduction
/Recap
Terminology:
 hosts and routers are nodes
 communication channels
that connect adjacent nodes
along communication path
are links
 wired links
 wireless links
 LANs
 layer-2 packet is a frame,
encapsulates datagram

data-link layer has responsibility of


transferring datagram from one node
to physically adjacent node over a link
EEEN30024 Lecture 9 2
Types of Errors
 An error occurs when a bit is received in
error
 i.e. 1 0 or 0  1
 A single-bit error occurs when a bit is
corrupted but its neighbours are correct
 A burst error occurs when a cluster of
two or more bits are corrupted
 burst errors are more common than single
bit errors
 burst errors are caused by, for example,
impulse noise (generally) and fading (in a
wireless network)
EEEN30024 Lecture 9 3

Error Detection
and Correction
 Detecting errors require that redundant, check bits have to
be added to blocks of data
 redundant as they do not carry data

 Error Detection
 having sufficient check bits to detect that a frame is in
error
 error correction (if required) managed by retransmission of
frame
 an error-detecting code

 Error Correction
 Transmit rather more check bits (a greater degree of
redundancy) to provide a means for errors to be corrected
 An error-correcting code, also known as forward error
correction
EEEN30024 Lecture 9 4
Block Codes
 A message of m bits
 A set of n check bits
 Gives rise to a c-bit (m + n) codeword
 2m valid codewords can be transmitted from the set of
2c codewords
 a received codeword that is in the set of 2c-2m invalid
codewords indicates an error
 For each pair of codewords that can be produced, we
can compute a useful quantity called the Hamming
distance
 i.e. the number of bits that differ between each pair
 e.g. 00011 and 01101 have a Hamming distance of 3
• XOR and count 1s
 The minimum Hamming distance between all pairs of
codewords in the set of 2m valid codewords is the
Hamming distance for the coding scheme
EEEN30024 Lecture 9 5

Hamming Distance:
Error Correction and Error
Detection
 If dc is the number of bits in error that can be
corrected in the codeword and
 dd is the number of bits that can be
detected in the codewords
 For a code with a minimum Hamming
distance dmin we can note that
 for error detection purposes, dd = dmin – 1
 for error correction purposes,

 so if dmin = 3, 1-bit and 2-bit errors can be


detected or 1-bit errors can be corrected
EEEN30024 Lecture 9 6
Example
 Suppose that m = 2 and n = 4 and we use the
codewords 000000, 000111, 111000 and
111111

 By inspection dmin is 3
 any 1-bit and 2-bit errors can be detected
 invalid codewords would be produced
 any single bit error can be corrected
 the codeword received will be ‘closer’ to that of
the original data than any of the other 3
codewords and that any 2-bit error cannot be
corrected with confidence
 since the codeword received may be ‘closer’ to
another valid codeword

EEEN30024 Lecture 9 7

Redundancy and Code


Rate
 The ratio of redundant bits to data bits
is called the redundancy of the code
 Given by n/m
• in the previous example the redundancy is 4/2 =
2
 The ratio of data bits to total bits is
called the code rate
 Given by m/c
• In the previous example the code rate is 2/6 =
0.333

EEEN30024 Lecture 9 8
Parity Checking

 A single bit is added to the block so that the


number of 1s in the code word is even (even
parity) or odd (odd parity)

 thus for the 7-bit character 1010100


 the even parity encoding of the parity bit is
1 to give 10101001
 and the odd parity encoding of the parity bit
is 0 to give 10101000

EEEN30024 Lecture 9 9

Parity Checking
 A parity bit produces a Hamming Distance
of 2
 for example if m is 2 we transmit (using even
parity)
• 00 as 000
• 01 as 011
• 10 as 101
• 11 as 110
 giving the codewords 000, 011, 101, 110 and a
Hamming distance of 2
 therefore the code can be used to detect single
bit errors, but provide no error correction

 Where m = 7 the redundancy of the code is


1/7 and the code rate = 7/8 = 0.875

EEEN30024 Lecture 9 10
Extending Parity Checking
to two dimensions
 When a burst error occurs (affecting several bits),
parity checking has a probability of 0.5 of detecting
the error
 performance can be improved if the data to be sent
is considered as an x by y matrix
 the parity is computed for each of the y columns in
addition to the x rows
 data is sent on a row by row basis
 provided that the burst error is not greater than x bit
durations and that only one burst error occurs in the
time to send the block, the burst error will be
detected
 even where multiple errors occur, the probability of
each of the x columns having the correct parity is 0.5
(2-1) and the probability of a block being in error and
being accepted is 2-x
EEEN30024 Lecture 9 11

2-D Parity Checking


Example
 Assume we are to send 1100 1100 1100 1100 and
compute the (even) parity for each 4-bit group
 this would give 11000 11000 11000 11000
 Corrupting 2 bits gives 11000 11110 11000 11000 with a
correct parity
 if a block is sent, the error is detected Parity
column

Parity row

Parity bits in error


EEEN30024 Lecture 9 12
Error Correcting Code
 From earlier discussion of the Hamming
Distance it is apparent that errors can be
corrected if

 So to correct single bit errors dmin = 3


 To maximise the efficiency of the code, the
smallest code number of check bits (n) is
required for a given message size
 The theoretical lowest limit for such a system
can be reached by using a Hamming Code
EEEN30024 Lecture 9 13

Hamming Code*
 Number all bits from 1 to c starting at the
most significant bit (left hand bit)
 the bits that are powers of two, 1, 2, 4, 8,
16, etc … are check bits that record parity
 Even or odd parity may be used
 the other bits hold the m bits of data and
each contributes to the check bits that
contribute to the value, for example
 3 is checked by bits 2 and 1,
 6 is checked by bits 4 and 2
 13 is checked by bits 8, 4 and 1
*additional information about Hamming Codes can be found in Chapter 3
of "Computer Networks" by Andrew S. Tanenbaum.

EEEN30024 Lecture 9 14
Hamming Code Coding
Example

data to send data transmitted

EEEN30024 Lecture 9 15

Hamming Code Error Correction

 set a counter to zero


 for each check bit (1, 2, 4, 8, etc) check value
 if value incorrect, add bit number to the
counter
 after all check bits have been examined the
counter contains the number of the bit in error
and it can be corrected by inversion
 the Hamming code corrects single bit errors

EEEN30024 Lecture 9 16
Hamming Code Error
Correction: Example

-bit 10 in error, therefore invert to correct

EEEN30024 Lecture 9 17

Hamming Code

 can correct single errors


 however, can be used to correct burst errors
by arranging consecutive codewords in a
matrix
 similar to two-dimensional parity idea seen
earlier
 transmit data a column at time rather than on
a row at a time
 a burst of noise will affect 1 bit in several
codewords rather than several bits in one
codeword

EEEN30024 Lecture 9 18
Error Detecting
Codes
 Error correcting codes seem quite appealing,
but there is a large overhead.

 Suppose that a Hamming code is used with a


block of 4096 bits, each 4096-bit block
requires 12 check bits to support single-bit
error correction.
 1MB of data requires 24,576 check bits.

 For single-bit error detection, a single parity


bit could be added to each block.
 1MB of data requires 2,048 check bits.

EEEN30024 Lecture 9 19

Error Detecting
Codes (continued)
 Parity checking may be used (especially in the
2D form described earlier (which gives rise to
more check bits)), but the more common
forms of error checking is by

 cyclic redundancy code (CRC code) – at


data link layer
• e.g. 802.3 Ethernet, 802.11 Wireless

 Internet Checksum - 1’s complement of


the 1’s complement sum of words –
above data link layer

EEEN30024 Lecture 9 20
Detecting Errors
– Block Coding

Block coding technique as check bits


are added to each frame
Collectively the data and check bits
are referred to as the codeword

EEEN30024 Lecture 9 21

CRC: Cyclic
Redundancy Code
 Given a m-bit message the transmitter generates an n-
bit sequence called the Frame Check Sequence
(FCS)
 the resulting c-bit frame (m followed by n) is exactly
divisible by a predetermined number (the generator
sequence)
 known to both sender and receiver
 the receiver receives the incoming frame, divides by
the generator sequence
 if the remainder is zero, there is no error in the
frame
 if the remainder is not zero, there is some error
 thus the FCS is appended to the message to give the
property that when the frame is divided by the
generator sequence there will be no remainder
EEEN30024 Lecture 9 22
Cyclic Redundancy
Code
 CRCs are often expressed in polynomial form
 the bits in a word represent the coefficients of a
polynomial of a dummy variable (x)
 For example, the byte 10100101 represents

 this is done as it best explains the arithmetic used


 it is possible to present CRCs using Modulo 2 Arithmetic
 this approach is followed here, before briefly
returning to polynomial form

EEEN30024 Lecture 9 23

CRC - Modulo 2
Arithmetic
Addition and Subtraction
 Binary addition – with no carries  XOR
 Binary subtraction – with no borrows 
XOR
 Thus
0011 + 0011 –
0110 0110
0101 0101

EEEN30024 Lecture 9 24
CRC - Modulo 2 Arithmetic
Explanation
 Define
 T = c-bit frame to be transmitted
 D = m-bit block of data, the message, the first m
bits of T
 F = the n-bit FCS, the last n bits of T
 P = a pattern of n + 1 bits, this is the divisor
• The generator sequence

EEEN30024 Lecture 9 25

CRC - Modulo 2 Arithmetic


Explanation
 We need T/P to have no remainder
 Now T=2n D + F
 Because we have the m bits of the message,
followed by the n bits of the FCS (F)
 2nD will shift D to the left by n places
 Suppose we consider the effect of dividing
2nD by P, this will yield a quotient (Q) and
remainder (R) of the form:

 because we are dealing with modulo 2


arithmetic the remainder must be at least 1
bit shorter than the divisor
EEEN30024 Lecture 9 26
CRC - Modulo 2 Arithmetic
Explanation
 Using the remainder as the FCS (i.e. F=R),
we have
 T = 2nD+R
 This satisfies the requirement for T/P to
have no remainder
 Note that in modulo 2
arithmetic x + x = 0
 Because anything XOR’d
with itself must give 0

EEEN30024 Lecture 9 27

CRC - Modulo 2 Arithmetic


Explanation

 to generate F (the FCS) divide 2n D by P


 at receiver divide T by P
 no remainder = no error

EEEN30024 Lecture 9 28
CRC - Modulo 2 Arithmetic
Example - Creation Q
 Message (D) = 11111001
2n D
1101/10011010000
10011010 1101
 Generator (P) = P 1001
1101 1101
1000
1101
 R = F, so send 2n D 1011
+R 1101
1100
 R = 101 1101
 i.e. 10011010101 1000
1101
101 R

EEEN30024 Lecture 9 29

CRC - Modulo 2 Arithmetic


Example – Reception – No error

 Divide T by P 11111001
1101/10011010101
1101
 No remainder so no 1001
error 1101
1000
1101
1011
1101
1100
1101
1101
1101
0

EEEN30024 Lecture 9 30
CRC - Modulo 2 Arithmetic
Example – Reception – with
errors
 Remainder is not 11110100
1101/10010000101
zero, hence error 1101
detected 1000
1101
1010
1101
1110
1101
1101
1101
001

EEEN30024 Lecture 9 31

CRC - Modulo 2 Arithmetic


Notes
 The generator P is 1-bit longer than the FCS.
 The pattern P is dependent on the type of errors, but the
most significant bit and the least significant bit must be
1.
 Errors will be detected as long as they are not
introduced such that the result is exactly divisible by P.
 An error is due to a bit being inverted, equivalent to the
XOR of the bit and 1 (addition in modulo 2), i.e. 0 + 1 =
1 and 1 + 1 = 0.
 If E = the error pattern (a c-bit frame, with a 1 in each
bit position that there is an error) a frame with an error
is given by
 Terr = T + E
 For E != 0, errors will not be detected if Terr is divisible
by P, which is equivalent to E being divisible by P
 the likelihood of this is low
EEEN30024 Lecture 9 32
CRC
Polynomials
 A similar explanation can be developed
using CRCs as polynomials
 See Stallings for details
 An understanding of the polynomials is
only required to understand the
specification of standard generator
polynomials
 For example, the standard CRC-16 is
 x16 + x15 + x2 + 1
 the 17-bit generator 11000000000000101,
which will lead to a 16-bit CRC
EEEN30024 Lecture 9 33

CRC-Polynomials- common forms


of generator polynomial
 There are a number of standard forms, e.g.
 For 8-bit characters CRC-16 and CRC-CCITT
are used (US and Europe respectively), these
result in a 16-bit CRC
 CRC-16 = x16+x15+x2+1
 CRC-CCITT =x16+x12+x5+1
 CRC-32 is used in IEEE 802 LAN standards
(e.g. Ethernet)
 CRC-32 =
x32+x26+x23+x22+x16+x12+x11+x10+x8+x7
+x5+x4+x2+x+1
EEEN30024 Lecture 9 34
Simpler
Checksums
 TCP, UDP and IPv4 use checksums to
detect errors
 Internet Checksum
 checksums are simpler than a CRC
 checksum is the 1’s complement of the 1’s
complement sum of all 16-bit words
involved in transmission
 see earlier lectures
 on reception the checksum is added to the
1’s complement sum of the 16-bit words
and if the result is 0, there is no error
EEEN30024 Lecture 9 35

Simpler Checksums
Internet Checksum
To give an example, work with bytes
rather than 16-bit words and assume
that 4 bytes are to be transmitted in
addition to the checksum
 4 bytes are
 10101010
 00001111
 01011010
 10010010

36
Internet Checksum Creation
 Add together the 4 bytes, 2  Take 1’s complement
at a time, using 1’s (i.e. invert all the
complement modulo 2 bits)
arithmetic; any carry out is
added to the LSB:  01011001
-this is the checksum
10101010 +
00001111
10111001 +
01011010
100010011 +
1
Carry out 00010100 +
added to
the LSB 10010010
10100110
EEEN30024 Lecture 9 37

Checksum checking
–no error
 Take data and  It’s 1’s complement so the
checksum byte and carry is added to the least
add together using 1’s significant end
complement addition 11111110 +
10101010 + 1
00001111 11111111
01011010
10010010  the result is 11111111 this
01011001 is one of the two 1’s
111111110 complement
1111 1 1 representations of zero (-0)
1  so the checksum is correct

EEEN30024 Lecture 9 38
Checksum checking
– with error
 Take data and checksum  It’s 1’s complement so the
byte and add together carry is added to the least
using 1’s complement significant end
addition 00111110 +
10101010 + 10
01001111 01000000
01011010 11111
10010010  the result is 01000000 this
01011001 is not 0,
1000111110  so the checksum indicates
an error
1 11 1 1
1 1
EEEN30024 Lecture 9 39

Lecture 9 Summary

Data Link Layer 2/3

 Error /detection
correction

EEEN30024 Lecture 9 40
Lecture 10:
Data Link Layer (3/3)

Learning Outcomes :

 Be able to explain the principles


behind the following :

 Link layer addressing


 Ethernet

Reading: K&R section 5.4 – 5.8

EEEN30024 Lecture 10 1

MAC Addresses and


ARP
 32-bit IP address:
 network-layer address
 used to get datagram to destination IP subnet
 MAC (or LAN or physical or Ethernet)
address: Media Access Control
 function: get frame from one interface to
another physically-connected interface (same
network)
 48 bit MAC address (for most LANs)
• burned in NIC ROM, also sometimes software
settable
EEEN30024 Lecture 10 2
LAN Addresses and
ARP
Each adapter on LAN has unique LAN address

1A-2F-BB-76-09-AD Broadcast address =


FF-FF-FF-FF-FF-FF

LAN
(wired or = adapter
wireless)
71-65-F7-2B-08-53
58-23-D7-FA-20-B0

0C-C4-11-6F-E3-98

EEEN30024 Lecture 10 3

LAN Address
(more)
 MAC address allocation administered by IEEE
 manufacturer buys portion of MAC address space
(to assure uniqueness)
 analogy:
(a) MAC address: like National Insurance
Number (UK)
(b) IP address: like postal address
 MAC flat address ➜ portability
 can move LAN card from one LAN to another
 IP hierarchical address NOT portable –can change
 address depends on IP subnet to which node is attached
 DHCP, etc
EEEN30024 Lecture 10 4
ARP: Address Resolution
Protocol
Question: how to find MAC  Each IP node (host,
address of a host, knowing router) on LAN has an
that host’s IP address? in-memory ARP table
 ARP table: IP->MAC
137.196.7.78
address mappings for
1A-2F-BB-76-09-AD
some LAN nodes
137.196.7.23 < IP address; MAC address;
137.196.7.14
TTL>
LAN  TTL (Time To Live):
71-65-F7-2B-08-53 time after which
58-23-D7-FA-20-B0
address mapping will
be forgotten (typically
0C-C4-11-6F-E3-98 20 min)
137.196.7.88

EEEN30024 Lecture 10 5

ARP protocol:
Same LAN (network)
 A wants to send  A caches (saves) IP->MAC
datagram to B, and B’s address pair in its ARP table
MAC address not in A’s until information becomes old
ARP table. (times out)
 A broadcasts ARP query  information that times out
packet, containing B's IP removed from the table
address (unless refreshed)
 dest MAC address =  table often viewable from
FF-FF-FF-FF-FF-FF command line program,
 all machines on LAN e.g. ‘arp –a’ on Windows
receive ARP query  ARP is "plug-and-play" :
 B receives ARP packet,  nodes create their ARP
replies to A with its (B's) tables without intervention
MAC address from an administrator
 frame sent to A’s MAC
address (unicast)
EEEN30024 Lecture 10 6
Addressing:
routing to another LAN
Walkthrough: send datagram from A to B via R.
-assume Ethernet connections
 focus on addressing - at both IP (datagram) and MAC layer
(frame)
 assume A knows B’s IP address
 assume A knows IP address of first hop router, R (how?)
 assume A knows MAC address of first hop router interface
(how?)
A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 7

Addressing:
routing to another LAN
 A creates IP datagram with IP source A, destination B

 A creates link-layer frame


MAC src: 74-29-9C-E8-FF-55
MAC dest: E6-E9-00-17-BB-4B with R's MAC address as
IP src: 111.111.111.111
IP dest: 222.222.222.222
destination, frame contains
A-to-B IP datagram
IP
Eth
Phy

A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 8
Addressing:
routing to another LAN
 frame sent from A to R  frame received at R,
datagram removed,
MAC src: 74-29-9C-E8-FF-55
passed up to IP
MAC dest: E6-E9-00-17-BB-4B
IP src: 111.111.111.111
IP dest: 222.222.222.222

IP IP
Eth Eth
Phy Phy

A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 9

Addressing:
routing to another LAN
 R forwards datagram with IP source A, destination B
 R creates link-layer frame
with B's MAC address as
destination, frame contains MAC src: 1A-23-F9-CD-06-9B
MAC dest: 49-BD-D2-C7-56-2A
A-to-B IP datagram IP src: 111.111.111.111
IP dest: 222.222.222.222
IP
IP Eth
Eth Phy
Phy

A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 10
Addressing:
routing to another LAN
 R forwards datagram with IP source A, destination B
 R creates link-layer frame
with B's MAC address as MAC src: 1A-23-F9-CD-06-9B
MAC dest: 49-BD-D2-C7-56-2A
dest, frame contains A-to- IP src: 111.111.111.111
B IP datagram IP dest: 222.222.222.222
IP
IP Eth
Eth Phy
Phy

A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 11

Addressing:
routing to another LAN
 R forwards datagram with IP source A, destination B
 R creates link-layer frame with MAC src: 1A-23-F9-CD-06-9B
B's MAC address as destination, MAC dest: 49-BD-D2-C7-56-2A
IP src: 111.111.111.111
frame contains A-to-B IP IP dest: 222.222.222.222
datagram IP
Eth
Phy

A B
R
111.111.111.111
222.222.222.222
74-29-9C-E8-FF-55
49-BD-D2-C7-56-2A
222.222.222.220
1A-23-F9-CD-06-9B

111.111.111.112 111.111.111.110 222.222.222.221


CC-49-DE-D0-AB-7D E6-E9-00-17-BB-4B 88-B2-2F-54-1A-0F

EEEN30024 Lecture 10 12
Ethernet
"dominant" wired LAN technology:
 cheap ~ £20 for NIC
 first widely used LAN technology
 simpler, cheaper than token LANs and ATM
 kept up with speed race: 10 Mbps – 10 Gbps

Metcalfe’s Ethernet
sketch

EEEN30024 Lecture 10 13

Star topology
 bus topology popular through mid 1990s
 all nodes in same collision domain (can collide with
each other)
 today: star topology prevails
 active switch in center
 each “spoke” runs a (separate) Ethernet protocol
(nodes do not collide with each other)

switch

bus: coaxial cable star

EEEN30024 Lecture 10 14
Ethernet Frame Structure
Sending adapter encapsulates IP datagram (or
other network layer protocol packet) in
Ethernet frame

Preamble:
 7 bytes with pattern 10101010 followed by
one byte with pattern 10101011
 used to synchronize receiver, sender clock
rates

EEEN30024 Lecture 10 15

Ethernet Frame Structure (more)


 Addresses: 6 bytes
 if adapter receives frame with matching destination
address, or with broadcast address (e.g. ARP
packet), it passes data in frame to network layer
protocol
 otherwise, adapter discards frame
 Type: indicates higher layer protocol (mostly
IP but others possible, e.g., Novell IPX,
AppleTalk)
 CRC: checked at receiver, if error is detected,
frame is dropped

EEEN30024 Lecture 10 16
Ethernet:
Unreliable, connectionless

 connectionless: No handshaking between sending


and receiving NICs
 unreliable: receiving NIC doesn’t send ACKs or
NAKs to sending NIC
 stream of datagrams passed to network layer can have
gaps (missing datagrams)
 gaps will be filled if app is using TCP
 otherwise, app will see gaps
 Ethernet’s MAC protocol: unslotted CSMA/CD

EEEN30024 Lecture 10 17

Ethernet CSMA/CD algorithm


1. NIC receives datagram 4. If NIC detects another
from network layer, transmission while
creates frame transmitting, aborts
2. If NIC senses channel and sends jam signal
idle, starts frame 5. After aborting, NIC
transmission If NIC enters exponential
senses channel busy, backoff: after nth
waits until channel idle, collision, NIC chooses K
then transmits at random from
{0,1,2,…,2 n-1}. NIC waits
3. If NIC transmits entire
frame without detecting K x 512 bit times, then
another transmission, returns to Step 2.
NIC is done with frame !
EEEN30024 Lecture 10 18
Ethernet’s CSMA/CD (more)
Jam Signal: make sure all Exponential Backoff:
other transmitters are  Goal: adapt retransmission
aware of collision; 48 bits attempts to estimated
Bit time: .1 microsec for 10 current load
Mbps Ethernet ;  heavy load: random
for K=1023, wait time is wait will be longer
about 50 msec  first collision: choose K
from {0,1}; delay is K·
512 bit transmission times
See/interact with Java
 after second collision:
CSMA/CD applet:
http://media.pearsoncmg choose K from {0,1,2,3}…
.com/aw/aw_kurose_net  after ten collisions, choose
work_2/applets/csmacd/ K from {0,1,2,3,4,…,1023}
csmacd.html
EEEN30024 Lecture 10 19

CSMA/CD efficiency
 Tprop = max prop delay between 2 nodes in
LAN
 ttrans = time to transmit max-size frame

 efficiency goes to 1
 as tprop goes to 0
 as ttrans goes to infinity
 better performance than ALOHA: and simple,
cheap, decentralized!
EEEN30024 Lecture 10 20
802.3 Ethernet Standards:
Link & Physical Layers

 many different Ethernet standards


 common MAC protocol and frame format
 different speeds: 2 Mbps, 10 Mbps, 100
Mbps, 1Gbps, 10G bps
 different physical layer media: fiber, cable

MAC protocol
application and frame format
transport
network 100BASE-TX 100BASE-T2 100BASE-FX
link 100BASE-T4 100BASE-SX 100BASE-BX
physical

copper (twister pair) physical fiber physical layer


layer
EEEN30024 Lecture 10 21

Ethernet Switch
 A link-layer device: more properly termed a
Link Layer Switch
 stores and forwards Ethernet frames
 Has a switch table
• examines incoming MAC addresses and selectively
forwards frames to one or more outgoing links,
according to table entries.
 self-learning
• no need to configure; “plug and play”.

 Transparent
 hosts are unaware of presence of switch.

EEEN30024 Lecture 10 22
Link Layer Switch
 Hosts have dedicated A
full-duplex
connection to switch. F B
 Ethernet protocol is
6 1 2
used but no collisions
 hosts can transmit 5 4 3
simultaneously E C
• the switch buffers
packets.
D
switch with six interfaces
(1,2,3,4,5,6)

EEEN30024 Lecture 10 23

Link Layer Switch


application
both are store-and-forward: transport
 routers: network-layer datagram network
devices (examine frame link
network-layer headers) physical link frame
 switches: link-layer physical
devices (examine link-
switch
layer headers)
network datagram
both have forwarding link frame
tables: physical
 routers: compute tables
using routing algorithms, application
IP addresses transport
 switches: learn network
forwarding table using link
flooding, learning, MAC
addresses physical

EEEN30024 Lecture 10 24
Manchester Encoding

 used in 10BaseT
 each bit has a transition
 allows clocks in sending and receiving nodes
to synchronize to each other
 no need for a centralized, global clock among nodes
 more later…
EEEN30024 Lecture 10 25

Lecture 10
Summary
Data Link Layer 3/3

 Link layer addressing


 Ethernet

EEEN30024 Lecture 10 26
Lecture 11:
Embedded Systems
Networks
Learning Outcomes :
 Be able to explain the following :
 Introduction to Embedded Systems IO
 Memory-mapped v Ported I/O
 Synchronous and Asynchronous Serial Bus
Protocols
 Serial and Parallel bus architectures
 Design issues for serial networks
 UARTS; bit rates v baud rates; “bit-banging”

EEEN30024 Lecture 11 1

Introduction
Embedded computing system: a system that includes
a programmable computer but is not itself a general-
purpose computer.

• microcontroller rather than general purpose


microprocessor
• includes I/O devices, on-board memory

• in general there are no standard inputs and outputs


like keyboards and screens that PCs have
• the system is usually dedicated to a well defined set
of tasks

Embedded systems are everywhere


• sales of processors sold for the general PC market are
dwarfed by those for embedded systems

EEEN30024 Lecture 11 2
Embedded Systems
 Some characteristics

• sophisticated functionality
• real-time operation
• low cost
• low power
• compact design

 Contain general and special-purpose processors

 Embedded systems are all around us. Examples:


• mobile phones, printers, domestic and household
appliances, cameras, set-top boxes, printers, etc
• have been since the 1970s (early microprocessors)
• some are complex involving 10’s of microcontrollers,
e.g. high-end automobiles

EEEN30024 Lecture 11 3

Embedded System I/O

 Communication can occur


 on-chip (‘network-on-a-chip’ or NoC)
• the application of networking methods on a single
piece of silicon
• i.e packet switching, routing, etc

 between devices on a PCB

 between more widely separated devices


• that are not physically near one another

 Briefly considering NoC first…

EEEN30024 Lecture 11 4
Network-on-Chip (NoC)

 NoC -communications within large VLSI systems


 a design trend for System-on-Chip (SoC)
 System-on-Chip
• a ‘scaled-up’ microcontroller with integration of
multiple processors, RAM, DMA, DSP, radio, etc
• implemented by full-custom, or semi-custom
techniques, e.g. Standard Cell, or FPGA

processor1 processor2

cache cache

special-purpose
memory memory ...
processor

Network

EEEN30024 Lecture 11 5

Network-on-Chip (NoC)
 applies the concepts of
large-scale networks to
embedded system-on- PE PE PE
chip
S S
 packet or virtual circuit
switching on a single PE PE PE
integrated circuit
S S
 packets are routed from
via network ‘fabric’ PE PE PE
consisting of switches
(‘routers’) and S S
inteconnection links
(wires) PE processing element
S switch

EEEN30024 Lecture 11 6
Embedded Systems I/O
 μC needs to talk with I/O
devices such as D/A Address
converter, EEPROM, LEDs… Data
μC
Read
 Memorymapped I/O Write
 devices are mapped to
specific memory Memory I/O Device
locations just like RAM
 uses load/store
instructions just like Address
accesses to memory Data
μC Port Select
 Ported I/O Read
 special bus line and Write
instructions I/O Port
 one or more Memory
addressable registers I/O Device
for control and data I/O Port usually included on-board microcontroller
adapted from Intel EEEN30024 Lecture 11 7

Memory-mapped I/O
 With memory-mapped I/O, one address space FFFF
is divided into two parts Memory

 some addresses refer to physical memory I/O D000


C000
locations
 other addresses actually reference
peripherals
• device controller registers, e.g. status,
Memory
read/write
 The I/O address-space is shared by many
peripherals
 some devices may need several I/O 0000
addresses
 CPU writes data to the appropriate I/O address
 address and data then transmitted along the
bus
 Each device monitors the address bus to see if
it is the target
EEEN30024 Lecture 11 8
Memory-mapped I/O
 Aspects of Memory-
mapped I/O

 programming simpler
 I/O looks just like
memory read/write
 must decide which
memory addresses are
used for I/O devices
 devices have relatively
high pin count for
data/address/control
• increases package size
and overall cost

from Windows XP Device Manager

EEEN30024 Lecture 11 9

Ported I/O
FFFFFFFF
 Aspects of Ported I/O

 separate address spaces


 simplifies number of connections
and provides common way Main
(protocol) of connecting memory
different or same type of I/O
devices
 need I/O or memory select
signals
 need special commands for I/O 00000000
 device pin count depends on
type of bus 0000FFFF
• parallel I/O
devices
• serial
00000000

EEEN30024 Lecture 11 10
I/O Bus Architecture
 Busses can be categorised in different ways:
serial/parallel, electrical characteristics, protocol used, etc.
 E.g. by synchronous/asynchronous :
 Synchronous bus transfers occur in relation to
successive edges of a clock
 Asynchronous bus transfers bear no particular timing
relationship
 Semisynchronous bus Operations/control initiate
asynchronously, but data transfer occurs synchronously

Bus

μC Device 1 Device 2 Device 3

image: Intel EEEN30024 Lecture 11 11

Synchronous Bus Protocol


 Transfer occurs in relation to successive edges of the system
clock, e.g.
 Memory address is placed on the address bus within a certain
time, relative to the rising edge of the clock
 By the trailing edge of this same clock pulse, the address
information has had time to stabilize, so the READ line is
asserted
 Once the chip has been selected, then the memory can place
the contents of the specified location on the data bus
Clock
stable stable
Address Instruction Addr Data Addr
decoding delay
Master (CPU) RD

Master (CPU) CS
unstable stable unstable stable
Data I-fetch data
access time
image: Intel EEEN30024 Lecture 11 12
Asynchronous Bus Protocol
 No system clock used
 Useful for systems where CPU
and I/O devices run at
different speeds Address
 Example: there's
I see you
got it
some
 Master puts address and Master data

data on the bus and then


raises the Master signal Slave I’ve
got I see you
 Slave sees master signal, it see I got it

reads the data and then


Data
raises the Slave signal
 Master sees Slave signal
and lowers Master signal write read

 Slave sees Master signal


lowered and lowers Slave
signal
Master – slave “handshaking”

image:Intel EEEN30024 Lecture 11 13

Bus Arbitration
 What happens if multiple
devices want access to the
bus? Bus
 Scheme 1: Every device
connects to the bus request line
and the first one there gets it μC Device 1 Device 2 Device 3

 Scheme 2: daisy chain the


Bus request line
devices devices further down
the daisy chain pass the request
to the CPU device's priority Bus
decreases further down the
daisy chain μC
Request
 Scheme 3: one bus request Device 1 Device 2 Device 3
Grant
line per bus and arbitrator
applies arbitration policy to
decide who gets bus next.
 Other schemes: many other
MAC protocols

image: Intel EEEN30024 Lecture 11 14


Protocols for
Embedded Systems networks
 Unlike in the Internet, where TCP/IP over Ethernet, WiFi,
3G, etc, dominates, there is no dominant protocol in the
embedded systems world.
 but there are certain industry-specific examples, e.g. CAN in
the automotive industry

 Many TCP/IP features are unnecessary or undesirable in


embedded networks
 flow and congestion control rarely seen
 unusual to see support for fragmentation/re-assembly
 stream abstraction seldom used
 embedded networks are more like UDP than TCP
 reliability of individual packets more important than building
reliability with re-transmission

EEEN30024 Lecture 11 15

Bus Architecture:
Serial v Parallel
 Speed
 On a parallel bus the speed of an 8-bit data transfer is in theory 8-times
faster than serial data transfer. In practice clock skew reduces the speed
to that of the slowest (lagging) link. Data only needs to be placed in a
latch and copied onto the data bus; most serial data transfer must be
converted from/to parallel form but is usually done on-chip at high speed.

parallel port

Output 1
Output 2
Output 3
.
μC .

image: Altera EEEN30024 Lecture 11 16


Bus Architecture:
Serial v Parallel

 Cost
 transmission channel costs such as data bus cable length, data bus
buffers, interface connectors, area occupied on microcontroller or printed
circuit board (PCB), parallel data communication is costlier.

 Bus length
 Noise and interference between the parallel lines (‘crosstalk’), worsens
with the length of the communication link. This places an upper limit on
the length of a parallel data connection that is usually shorter than a serial
connection. Bandwidth and signal-to-noise ratio are generally lowered by
these effects. A serial bus usually allows devices to be attached over much
longer distances. Parallel bus more commonly seen on-chip or on the
same PCB.

For these reasons serial bus networks predominate for embedded


systems.

EEEN30024 Lecture 11 17

Serial Networks
 Examples of serial networks :

image: Philips EEEN30024 Lecture 11 18


Serial Networks –design issues

 Design considerations with serial networks:

 data rate & error rate


• impacts on the maximum length of the bus
 fault tolerance
 bit sequence (most/least significant bit first)
 how to select a device
• separate chip-select line or through software protocol ?
 synchronization
• separate clock line or clock embedded in the data
stream

EEEN30024 Lecture 11 19

Serial Networks –design issues


(continued)

 data transmission types:


 single line, switching between “high” and “low”
• simple, in principle only a single wire required (plus ground)

 differential line –both lines change voltage simultaneously


but in opposite directions
• more wires needed but allows for greater cable lengths than with
single line

 bus termination
• both ends terminated with matching impedances (differential
signalling)
• unterminated, or terminated at one end only (typical with single-ended
busses)

EEEN30024 Lecture 11 20
Embedded I/O devices for serial
communications
 Data within a microcontroller is mostly transferred in parallel
• there is need for parallel->serial and serial->parallel conversion
• carried out by a UART -basis for most serial communication hardware
-Universal Asynchronous Receiver Transmitter
• originally handled by a dedicated chip, nowadays integrated on-chip

Data out Data in

8 8

Transmit Data Received Data


Buffer Buffer

Tclock Serial Data Serial In/Parallel Out Rclock


Parallel In/Serial Out
Shift Register Shift Register

TRANSMITTER RECEIVER

EEEN30024 Lecture 11 21

UART
 Commonly used for asynchronous communication
• between an embedded system and another device or embedded system
• supports protocols such as RS232, RS422, RS423 (considered later);
these support voltages of up to +/- 25V; UART does the voltage level
shifting required.
• supports simplex, half- and full-duplex protocols
• simplex : data sent in one direction only
• half-duplex : data sent in both directions, but not at the same time
• full-duplex : data can be sent in both directions simultaneously

Tclock1 Rclock2
Transmitter Receiver
Data Bus Data Bus

Rclock1 Tclock2
Receiver Transmitter

UART UART

EEEN30024 Lecture 11 22
UART
 UART is also responsible for framing the data
• E.g. 1 start bit, 8 data bits 1 stop bit
– depends on actual protocol
• an additional parity bit optionally before stop bit
• start and stop bits used to separate frames

Data
bits

Message

10110110001
UART UART

EEEN30024 Lecture 11 23

MicroChip USART
 Basically a UART with support for synchronous serial
communication in half-duplex mode
 clock is sent with data (Tx pin)
 mode of operation selectable through software control of a register
 baud rate settable through the Baud Rate Generator –a component
of the USART

 High-level software control is provided through C library


functions, e.g.
 OpenUSART()
 BusyUSART
 putcUSART()
 getsUSART()
 CloseUSART()
-see MicroEngineering 2 lecture notes, PN Green, 2011.

EEEN30024 Lecture 11 24
Bit Rate vs. Baud Rate
 Bit Rate: number of data bits are transmitted per second
 serial link speed, e.g. 9600bps to 1.5 Mbps, typically
 Baud Rate: number of symbols are transmitted per second
 rate at which signal on line changes
 a symbol may be represented by a voltage level, a sine
wave’s frequency or phase, etc.
 These may be different
 Extra symbols (channel changes) may be inserted for
framing, error detection, acknowledgment, etc. These
reduce the bit rate
 A single symbol might encode more than one bit. This
increases the bit rate.
• e.g. multilevel signaling, quadrature amplitude
modulation, phase amplitude modulation, etc.
• other encoding schemes considered later

EEEN30024 Lecture 11 25

"Bit Banging"
 When a microcontroller has only limited (e.g. single UART) or
no support for adding devices to a serial interface

 Use software for communication instead of dedicated hardware


 known as “Bit Banging”
 in principle can program different protocols with no hardware
changes
 you have complete control over the whole communication process,
and choose to implement only a subset of the protocol if desired.

 Select one or more spare I/O pins for “transmit” and “receive”
 transmitting is done by alternating the transmit pin at the desired
baud rate
 receiving is done by sampling the receiver pin at a regular interval
-e.g. if the rate is 9600bps the sampling interval is 1/9600 s
(104us)

EEEN30024 Lecture 11 26
"Bit Banging"
 Pseudo-code for algorithm for sending a byte:

start
repeat
make Tx pin Low (Start Bit)
wait for duration corresponding to baud rate
send data bit
wait for duration corresponding to baud rate
until all eight data bits haven’t been sent
send Stop Bit
wait for duration corresponding to baud rate.
make Tx pin High
stop

EEEN30024 Lecture 11 27

"Bit Banging"

 In practice bit banging has problems

 depending on the protocol chosen, the code can be


complex, especially in a multi-master environment
 the microcontroller is tied-up controlling the pin(s) at the
expense of other tasks
 more memory is used
 more processing power is consumed
 serving other tasks and interrupts leads to timing errors
• there will be more jitter and glitches

EEEN30024 Lecture 11 28
Lecture 12:
Asynchronous Serial
Networks
Learning Outcomes :
 To compare and contrast synchronous and
asynchronous digital communication
 To explain the purpose, characteristics and
applications of the following Asynchronous
Serial Networks
 RS-232
 RS-422
 RS-485
 USB, FireWire

EEEN30024 Lecture 12 1

Asynchronous and
Synchronous Transmission

 timing problems require a mechanism to synchronise


the transmitter and receiver
 receiver samples the data stream at bit intervals
 if clocks are not precisely aligned, drifting will
sample at wrong time resulting in errors

 two solutions to synchronizing clocks:

EEEN30024 Lecture 12 2
Asynchronous Transmission
 no common clock between sender and receiver
 data are transmitted one character at a time
 each character is 5 to 8 bits in length
 receiver has the opportunity to resynchronize at
the beginning of each new character

 simple and cheap


 requires overhead of 2 or 3 bits per character (~20%)

 the larger the block of bits, the greater the


cumulative timing error

 good for data with large gaps (e.g. keyboard)


EEEN30024 Lecture 12 3

Asynchronous Transmission

receiver’s clock is 6% faster


than the sender’s.

from Stallings, Fig. 6.1, 8th ed. EEEN30024 Lecture 12 4


Synchronous Transmission
 block of bits transmitted in a steady stream without start and
stop codes
 clocks must be synchronized to prevent drift
 could use separate clock line
• but may be subject to timing errors over long distances
 or embed clock signal in data
• using an encoding technique e.g. based on Manchester or
differential Manchester encoding (see later)
 need to indicate start and end of block
 use preamble and postamble bit patterns
 frame is data plus preamble, postamble, and control
information
 more efficient than asynchronous for large blocks of data

from Stallings, Fig. 6.2 8th ed. EEEN30024 Lecture 12 5

RS-232

 A data communications standard dating from the


1960’s, but still used today and the basis for modern
versions

 The standard defines the following elements:


• handshaking signals
• direction of signal flow
• types of communication devices
• connectors and interface mechanical considerations
• electrical signal levels

 Related standards include RS-422 and RS-485


 these have different electrical interfaces allowing for higher
speeds and greater distances

EEEN30024 Lecture 12 6
RS-232
 Digital data exchange between a centrally located
mainframe computer and a remote computer terminal,
or between two terminals without a computer involved.
 originally over an analog (voice) telephone line, hence
modems at each end that connected ‘data terminal
equipment’ (DTE) and ‘data communication equipment’
(DCE). Lots of different manufacturers hence the need for
a standard to ensure compatibility.
 typical speeds (baud): 9600, 14400, 19200, 38400,
57800, 115200

DB25 : 25-pin
connector

image: CAMI Research Inc. EEEN30024 Lecture 12 7

RS-232 Signals
 Common 25 pin “D-shell” connector pin-out used for
asynchronous data communications.
 not all signals strictly necessary –usually a common subset are used
 9-pin connector more common nowadays (called “DB9”)

Pin Signal
1 PGND (Protective Ground)
2 TXD (Transmit Data)
3 RXD (Receive Data)
4 RTS (Ready To Send)
5 CTS (Clear To Send)
6 DSR (Data Set Ready)
(serial port - PC side)
7 SG (Signal Ground)
8 CD (Carrier Detect)
“DB25” connector
20 DTR (Data Terminal Ready)
22 RI (Ring Indicator)

EEEN30024 Lecture 12 8
RS-232 Signals
 Architecturally RS-232 is a
DB9 : 9-pin
bi-directional point to point connector

link.
(serial port - PC side)

 Two independent channels


are established for two-way
(full-duplex)
communications.
 RS-232 carries signals used
for flow control (RTS, CTS)
and modem control (DCD,
DTR, DSR, RI).

EEEN30024 Lecture 12 9

RS-232 Serial transmission


protocol
Signal Purpose
DTR –Data Terminal Ready DTE ready to be connected
DCD –Data Carrier Detect DCE is connected
DSR –Data Set Ready DCE ready to receive
commands
RTS –Request to Send DTE request to send data
CTS –Clear to Send acknowledge RTS
Tx –Transmitted Data Carry data from DTE/DCE
Rx –Received Data Carry data from DTE/DCE

common sub-set of signals shown

EEEN30024 Lecture 12 10
RS-232 Hardware Flow Control
 Prevent transmitter overflowing receiver’s buffer.

 Hardware flow control uses RTS/CTS :


 the transmitting end activates RTS to inform the
receiving end that it has data to send
 if the receiving end is ready to receive, it activates
CTS
Are you ready to
RTS receive?
CTS
RTS
transmitter

receiver
CTS No

RTS
CTS Yes

TD
Send RD
character

EEEN30024 Lecture 12 11

RS-232 Hardware Flow Control


- Example with DTR, DSR

 Steps:
 1. DTE (computer) sets DTR to make a  7. DTE has no further data to send; drops
connection with the DCE (modem). RTS.
 2. DCE accepts and replies with DSR.  8. DCE acknowledges by dropping CTS.
 3. DTE sends RTS.  9. DTE ready to send data again.
 4. DCE is ready and replies with CTS.  10. DCE acknowledges with CTS.
 5. DCE’s buffers are full; drops CTS to  11. DTE has no further data to send.
signal to DTE to stop sending data.  12. DCE drops CTS.
 6. DCE’s buffers cleared; raises CTS again.  13. DTE drops DTR to terminate
connection.
 14. DCE drops DSR.

Image from: http://www.z80.info/1656.htm EEEN30024 Lecture 12 12


RS-232 Software Flow Control
 Software flow control uses “Xon” and “Xoff” :
 Xon and Xoff are ASCII characters
 when the buffer within the receiving end is nearly full, Xoff
is sent to the transmitter to ask it to stop
 when data have been processed by the receiver and the
buffer has space again, Xon is sent to the transmitter to
notify it to resume
 advantage: only three wires are required (Tx, Rx and SG
(signal ground) transmitter

receiver
x-off

x-on

data
transmission
EEEN30024 Lecture 12 13

RS-232 Cables

• When two serial ports are connected, the data rate, the
number of data bits, whether parity is used, the type of
parity, and the number of stop bits must be set properly
and identically on each UART.

• Proper cables must be used. Common types are


 full DTE – DCE connection.
 DTE – DTE null-modem connection.
 minimal null-modem connection.

‘null-modem’ means no modem


used: this is DTE-DTE

EEEN30024 Lecture 12 14
RS-232 Interconnects

DB9 DB25 DB25 DB9


DTE DTE DCE DCE
TxD 3 2 2 3 TxD
RxD 2 3 3 2 RxD
SG 5 7 7 5 SG
RTS 7 4 4 7 RTS
CTS 8 5 5 8 CTS
DCD 1 8 8 1 DCD
DSR 6 6 6 6 DSR
DTR 4 20 20 4 DTR

Full DTE – DCE

EEEN30024 Lecture 12 15

RS-232 Interconnects

DB9 DB25 DB25 DB9


DTE DTE DTE DTE
TxD 3 2 2 3 TxD
RxD 2 3 3 2 RxD
SG 5 7 7 5 SG
RTS 7 4 4 7 RTS
CTS 8 5 5 8 CTS
DCD 1 8 8 1 DCD
DSR 6 6 6 6 DSR
DTR 4 20 20 4 DTR

DTE – DTE null-modem


EEEN30024 Lecture 12 16
RS-232 Interconnects

DB9 DB25 DB25 DB9


DTE DTE DTE DTE
TxD 3 2 2 3 TxD
RxD 2 3 3 2 RxD
SG 5 7 7 5 SG
RTS 7 4 4 7 RTS
CTS 8 5 5 8 CTS
DCD 1 8 8 1 DCD
DSR 6 6 6 6 DSR

minimal null-modem
EEEN30024 Lecture 12 17

RS-232 Physical
RS-232 Logic Levels:
Mark (logic 1) -25 to –3 volts
Space (logic 0) +25 to +3 volts

RS-232
TTL logic TTL
Logic levels Logic
levels
levels
RS-232 uses a single voltage
relative to ground to indicate data:
called ‘single-ended’ signalling
Least
Significant Bit
Space
when the transmitter is not
Mark sending anything, it holds
the line at mark level,
start bit data bits
also called idle level.

EEEN30024 Lecture 12 18
RS-232 Limitations

• large-amplitude, bipolar voltage swings complicate power supply


and driver design

• non-differential signaling limits noise immunity

• cable length typically limited to 15m, more with low-capacitance


cables.

• slower than modern serial interfaces, such as USB

• no standard way to connect more than two devices on one bus

EEEN30024 Lecture 12 19

RS422 Standards
 The RS-422 standard defines a balanced (or differential) data
communications interface using two separate wires for each
signal
 used in point-to-point links and uses same signals as RS-232 with
a different electrical interface specification
 Due to the high noise immunity of the RS-422 standard, high
data speeds and long distances can be achieved.
 The RS-422 specification allows reliable serial data
communications for:
 distances of up to 1200 meters
 data rates of up to 10 Mbps
 -6V to +6V nominal signal swing
 up to ten receivers can be attached
 RS-422 uses two separate twisted pairs (Tx and Rx)
 the transmitter translates the single input signal into a pair
of outputs that are driven 180° out of phase.
 the receiver, a differential amplifier, recovers the signal as the
difference in the voltages on the two lines.

EEEN30024 Lecture 12 20
RS-485

• uses differential signalling

• provides for multiple masters, so more like a bus than a


point-to-point link

• speed and distance similar to RS-422

• more common in data acquisition and control applications


than RS-232

• the standard only specifies the electrical characteristics of


driver and receiver
• there is no specification for a protocol
• there are interconnect systems that use RS-485 as a
physical layer specification, e.g. ModBus, ProfiBus

EEEN30024 Lecture 12 21

RS-485

 RS-485 interface has tri-state capability, so it can be used


in multi-drop systems (multiple slaves/masters)
 RS-485 can be half or full duplex and has a 2- or 4-wire
version
 the 2-wire version uses a single twisted pair; the 4-wire
version uses two twisted pairs
 RS-485 systems usually consists of a master and a slave
 slave devices have a unique address and will only respond
to requests from the master
 slaves never initiates communication
 tri-State
 logic 0
 logic 1
 high impedance (or disconnected) state
 DB9 connector terminal used:

EEEN30024 Lecture 12 22
RS-485 v RS-422

Resistor values are representative


Full-duplex operarion also possible

image: EC Data Technologies EEEN30024 Lecture 12 23

USB :
Universal Serial Bus
 Aim: unify the plethora of PC interconnect methods to
PCs that existed in the 1990s
vdd,gnd
 4-wire serial bus
 uses differential signalling
 a number of versions since 1995
 now USB 3.0
 speed up to 480Mbps
 hot-pluggable devices (plug & play)
 supports up to 127 external devices
 limited by 7-bit address
 bus provides power and ground D+, D-

EEEN30024 Lecture 12 24
USB Bus topology
PC

 Tiered star structure (max 6 tiers), of point-to-point links


 Bus expanded by Hubs
 these provide further attachment points
 Hub counts as one device
EEEN30024 Lecture 12 25

USB devices
 PC ‘host’ serves as master
 Devices cannot initiate data
transfers
 must wait to be asked by the
host
 no direct communication
between USB devices
 Each device has a unique
address
 data is sent in packets
 When the host is transmitting
each device on the bus sees it
 data is relayed/repeated by
the hub(s) down the chain

EEEN30024 Lecture 12 26
USB data flow

hardware/software
interface

EEEN30024 Lecture 12 27

USB Data flow types


 Control transfers
 Send commands to devices/configure devices at attach time
 Bulk data transfers
 generate or consume large data. Error detection and retries
included. Example: file transfer
 Interrupt data transfers
 small, limited-size transfers. Example: event notification;
echo from device
 Isochronous data transfers
 continuous and irregular streamed data. Example: voice
 USB protocol is complicated
 USB specification includes time-critical operations
 not practical to implement in software
 dedicated hardware –referred to as a ‘Serial Interface
Engine’ (SIE), implemented in silicon, handles the functions

EEEN30024 Lecture 12 28
FireWire

 Used by Apple
 Based on IEEE 1394
 a serial bus interface designed for high speed
communications
 ‘competition’ to USB
 similar speeds
 plug & play
 support up to 63 devices
 differential signalling and provides power
 comparison to USB
 USB is host-based(must be connected to computer),
Firewire is peer to peer (two devices can be connected
directly)

EEEN30024 Lecture 12 29
Lecture 13:
Examples of Synchronous
Serial Networks
Learning Outcomes :

 Be able to explain the purpose,


characteristics and applications of the
following Synchronous Serial Networks

 SPI Bus
 I2C-Bus

EEEN30024 Lecture 13 1

Introduction

 Synchronous communication protocols are ones where


the transmitter sends a clock signal with the data:
- either as a separate signal
- or embedded within the data stream

 The receiver knows where frames start and finish, so


start and stop bits are sometimes unnecessary

 In an embedded system synchronous communications


are usually used over short distances
 typically between integrated circuits on the same
PCB
 consequently the maximum data rates possible are
potentially higher than asynchronous systems

EEEN30024 Lecture 13 2
SPI Bus
Serial Peripheral Interface
 A four-wire interface used primarily for synchronous serial
communication of a host processor and peripherals

 A 'master' – 'slave' system


 Found on many microcontrollers
 e.g. MicroChip PIC family
 Popular
 many SPI-enabled devices: ADC/DAC converters, EEPROMs, Real
Time Clocks, Sensors (Pressure, Temperature)

image: IBM EEEN30024 Lecture 13 3

SPI : the concept


 To initiate data transfer, the master starts the clock and
selects a slave
 Data may be transferred in either or both directions
simultaneously

Master SCLK Slave

SS

MISO MOSI MOSI MISO

MOSI: Master Out Slave In


MISO: Master In Slave Out
SCLK: Serial Clock
SS: Slave Select

EEEN30024 Lecture 13 4
SPI
 In general devices can transmit and receive at the same
time
 e.g. an EEPROM
 some devices are receive-only, e.g. a display

 Slave Select (SS) is used to activate an individual slave.

 Multi-master mode is possible


 although only one device can control the bus at any one
time

 Devices can be simple shift registers or more complex


subsystems
 data can be control codes or data values
 the length of the shift registers is not specified from device to
device (but are normally 8 bits or multiples thereof)

EEEN30024 Lecture 13 5

SPI
 Scenario with single master and multiple slaves:

Master SCLK SCLK Slave 1


(microcontroller) MOSI MOSI
MISO MISO
SS1 SS1
SS2
SS3

SCLK Slave 2
MOSI
MISO
MOSI: Master Out Slave In SS2
-data is sent out if the device is a Master,
but received in if it’s a slave
MISO: Master In Slave Out
-data is received in if the device is a
Master, but sent out if it’s a slave
SCLK: Serial Clock –data is shifted on
either the rising or falling edge
SCLK Slave 3
SS: Slave Select –usually this is active
low. MOSI
MISO

EEEN30024 Lecture 13 6
SPI
 Scenario with single master and multiple slaves in a cascade
(or 'daisy-chain') configuration:
Master SCLK SCLK Slave 1
(microcontroller) MOSI MOSI
MISO MISO
SS SS1

SCLK Slave 2
MOSI
MISO
MOSI: Master Out Slave In SS2
-data is sent out if the device is a Master,
but received in if it’s a slave
MISO: Master In Slave Out
-data is received in if the device is a
Master, but sent out if it’s a slave
SCLK: Serial Clock –data is shifted on
either the rising or falling edge
SCLK Slave 3
SS: Slave Select –usually this is active
low. MOSI
MISO

EEEN30024 Lecture 13 7

SPI
 The master generates the slave select signals using
 general-purpose discrete input/output pins
 on-chip subsystem logic (eg MSSP on the MicroChip PIC).

 SPI is simple
 no communication protocol
-no specification for master-slave dialog
-no built-in addressing scheme
-no acknowledgement mechanism or flow control
-the clock can vary without disrupting the data. The data rate
will simply change along with the changes in the clock rate –
useful when the microcontroller is being clocked imprecisely,
such as by an RC oscillator.

 Custom communication protocols can be created “on top”


 programming is done either via library functions, or old-
fashioned 'bit banging'
EEEN30024 Lecture 13 8
SPI : MicroChip PIC
 PIC 18F8722 SPI is implemented as part of the Master Synchronous
Serial Port (MSSP) module:

SDO
RC5/SDO

SDI
SSPSR RC4/SDI

support for SPI is


provided through C library
SSPBUF functions, e.g.
 OpenSPI()
SCK  WriteSPI()
RC3/SCK
Control RA5/SS  ReadSPI()
SS  CloseSPI()
-see MicroCompEng 2
lecture notes, PN Green.
SDO : MOSI
SDI: MISO
SCK: Serial Clock
SS: Slave Select

EEEN30024 Lecture 13 9

SPI
Advantages:
 Fast and simple
 fast for point-to-point connections with full duplex
communication
 suited to data that is streamed rather than record-oriented

 no addressing/simple to implement

 widely supported

Disadvantages :
 multiple master configurations are complicated
 no acknowledgement ability
 no inherent arbitration
 no flow control
 short distances only (e.g. same PCB)

EEEN30024 Lecture 13 10
I2C-Bus
Inter-Integrated Circuit Bus

 Developed by Philips Semiconductor for TV sets in


the 1980’s

 I2C bus devices include EEPROMs, thermal sensors,


and real-time clocks

 Used as a control interface to signal processing


devices that have separate data interfaces, e.g. RF
tuners, video decoders and encoders, and audio
processors. I2C is widely used with a large number
of different device categories.

 The I2C bus has three speeds:


 Slow (under 100 Kbps)
 Fast (400 Kbps)
 High-speed (3.4 Mbps) – I2C v.2.0

EEEN30024 Lecture 13 11

I2C
+Vss

Rp Rp
Device 1 Device 2 Device 3
Microcontroller

SCL
SDA

each device has a unique address


open drain/collector
input

Gnd
output

 2-wire serial bus – serial data (SDA) and serial clock (SCL)

 Half-duplex, synchronous, multi-master bus

 No chip select or arbitration logic required

EEEN30024 Lecture 13 12
I2C
typically 5V

3mA typical max current


handled by output transistor
 Lines pulled high via resistors, driven down via open-drain drivers
(wired-AND)
 resistor values chosen for speed
-typically 2KΩ, 4K7Ω, 10KΩ, etc.
 Speed: up to 100KHz (standard mode), up to 400KHz (fast mode),
up to 3.4MHz (high speed mode)
 Several microcontrollers come with built-in support for I2C
 e.g. MicroChip PIC (via MSSP module)
 if not, have to use spare pins/ports and rely on "bit banging",
or use a separate bus controller device
image: Philips EEEN30024 Lecture 13 13

I2C Protocol
 Devices are either masters or slaves
 master initiates data transfers
 master always drives SCL
 multiple-master configurations possible but not common

 Data transfer begins with a Start sequence and ends with


a Stop sequence:

The start sequence and stop sequence are the only places where
the SDA (data) is allowed to change while the SCL (clock) is high.
When data is being transferred, SDA must remain stable and not change
whilst SCL is high. Start and Stop mark the beginning and end of a
transaction with the slave device.

EEEN30024 Lecture 13 14
I2C Signals

• Start – high-to-low transition of the SDA line while SCL line is high
• Stop – low-to-high transition of the SDA line while SCL line is high
• Data – transition takes place while SCL is slow, valid while SCL is high

Data are placed on SDA and transferred in sequences of 8 bits starting with
the MSB (Most Significant Bit). The SCL line is then pulsed high, then low.
For every 8 bits transferred, the device receiving the data sends back an
acknowledge Bit (ACK), so there are actually 9 SCL clock pulses to transfer
each byte. If the ACK bit sent by the receiving device is low, then it has received
the data and is ready to accept another byte. If it does not drive the line low,
and leaves it high then it is indicating it cannot accept any further data and the
master should terminate the transfer by sending a stop sequence.

EEEN30024 Lecture 13 15

I2C Signals

 Data transfer starts with the master transmitting the address


of the slave
 every device has an address (7 bits in standard version, 10 bits in
extended version) -bit 8 of address signals read or write
 Address bits A3-A6 select the device type, e.g.
 1010 for EEPROM devices
 0111 for LCD controllers
 ..etc
-leaving address bits A0, A1, A2 for device selection

EEEN30024 Lecture 13 16
I2C Protocol

 Master sends out Start sequence


 devices are alerted and listen for their address –the slave
that matches continues the transaction while others ignore it
 Depending on the device, the master may then have to send
out an internal address –e.g. for EEPROMs
 The master can then send the data byte(s)
 for multiple bytes the slave will typically increment an
internal register address after each byte
 when finished, the master sends a Stop sequence

 Typical flow:
1. Send Start sequence
2. Send the I2C address of the slave
3. Send an internal register address (if necessary)
4. Send the data byte(s)
5. Send the Stop sequence

EEEN30024 Lecture 13 17

I2C transmissions
single-byte write

S 7-bit address R/W A data A P


R/W = 0; A sent by slave
to microcontroller
multi-byte write

S 7-bit address R/W A data A data P

single-byte read

S 7-bit address R/W A data A P


R/W = 1; A sent by microcontroller
to slave; the last byte is not acknowledged
multi-byte read

S 7-bit address R/W A data A data /A P

EEEN30024 Lecture 13 18
I2C Bus Arbitration
 Sender listens while transmitting.
 If two masters generate a Start at the same time there will be
a conflict. Arbitration is done by monitoring SDA:

Data1 sent by Master 1

Data2 sent by Master 2

image: Philips EEEN30024 Lecture 13 19

I2C
Clock Stretching

 When the master issues a read


 the slave places the data on the bus

 but the master controls the clock

 If the slave is not ready, the master must wait for the slave
 if the slave is another microcontroller this could take a long
time, e.g. tens of microseconds.
 rather than have the master issue lots if unnecessary
clock pulses, the slave is allowed to hold the clock line
down, called clock stretching
 once the slave has the data ready it releases the clock

 this is normally handled automatically in the hardware of


the microcontroller.

EEEN30024 Lecture 13 20
I2C
Advantages:

 simple hardware and protocol


 suitable for on-board or off-board communication
 suited to data that is record-oriented
 addressing scheme enables easy addition of devices
 cost and complexity do not scale up with the number of
devices
 arbitration for multiple master configurations
 widely supported

EEEN30024 Lecture 13 21

I2C

Disadvantages :

 limited address space


 bus length limited but can be extended with I2C
repeater/hub
 dynamic addition/removal of devices has to be done with
care
 Lack of inventory function (e.g. similar to ARP in TCP/IP)
makes it difficult to handle a dynamic population.
 overhead of flow control inefficient in simple
configurations and a direct-link interface such as SPI
might be preferred.

EEEN30024 Lecture 13 22
I2C: MicroChip PIC

 PIC 18F8722 I2C is implemented as part of the Master Synchronous


Serial Port (MSSP) module:

RC4/SDI/SDA
support for SPI is
provided through C
SSPSR library functions, e.g.
RC3/SCL
 OpenI2C()
 WriteI2C()
SSPBUF  ReadI2C()
 StopI2C()
-see lab 2 notes
SSPCON1 Select master/slave
mode

EEEN30024 Lecture 13 23
Lecture 14:
CAN, LIN

Learning Outcomes :

 To be able to explain the purpose,


characteristics and applications of the
following Industrial Serial Networks

 CAN
 LIN

EEEN30024 Lecture 14 1

Introduction
 Industrial embedded systems applications often have
real time characteristics that impact on communications
requirements
 time-critical aspects where a guaranteed response
within strict time constraints is required
 reliability and safety are extremely important

 Certainly true in the automotive industry


 most modern vehicles have several electronic control
units that are networked using serial communication
protocols
 here we look at two examples: CAN and LIN
 CAN -Controller Area Network
 LIN -Local Interconnect Network

EEEN30024 Lecture 14 2
CAN
 Two-wire (twisted pair), bidirectional serial-bus
 differential signalling

 Originally developed in 1989 by Bosch for automotive use

ECU : Electronic Control Unit

 Without CAN some vehicles would have < 3km of wires


 inappropriate to connect all pairs of communicating devices with their own wires
- O(n2) wiring
Image: TI EEEN30024 Lecture 14 3

CAN
 Originally developed in 1989 by Bosch for automotive use
 Mostly used in passenger cars, but also lots of non-automotive uses
-farm and construction machinery
-printing machines, railway systems
-building automation,
-production and packaging equipment
-domestic goods, etc…

 Standardized internationally:
- CAN 2.0A: ISO11519 — low speed, <250Kbps("Basic CAN")
- CAN 2.0B: ISO11898 — high speed, <1Mbps ("Full CAN")

 Usage: >>100,000,000 CAN 'nodes' /year


- over 80% automotive

Image: Renesas EEEN30024 Lecture 14 4


CAN
Low cost
 low wiring cost
 low hardware cost
– lots of CAN nodes available
– some microcontrollers have
CAN interfaces built in

 (shielded) twisted-pair cabling


provides reduced sensitivity to
interference
 if EMI is injected into the bus,
both signals move together

Scalable network
 no limit in principle to the
number of nodes, although
typically< 40 per network

Image: Renesas EEEN30024 Lecture 14 5

CAN Protocol
 CAN does not specify a
physical interface
 only the data link layer

partially implemented by
higher-level protocols,
e.g. CANOpen, J1939,
DeviceNet

defined by CAN protocol

Image: Renesas EEEN30024 Lecture 14 6


CAN Node
 A CAN node doesn’t have an address CAN Node

 it has buffers (called "mailboxes") that


have pre-assigned identifiers
 the identifier defines the content type firmware
of the message and its priority
 each CAN message carries the mailbox[id_a]
identifier of the intended target device mailbox[id_b]
 multiple nodes can have a mailbox mailbox[id_c]

with the same identifier mailbox[id_d]

 when a transmitter at a CAN node


sends a data frame, it broadcasts that
message to all nodes on the bus. transceiver
However, only those nodes configured
to receive the identifier in that
message will accept and save the data.
All other nodes don’t do anything with
the data; they ignore it.
CAN bus
EEEN30024 Lecture 14 7

CAN Node

 The next diagram below illustrates a transmitting node and two


receiving nodes.

 The middle node has a receiver mailbox set to an identifier that


matches the transmitted identifier, so it accepts the data frame.
The node on the right has a receiver mailbox set to a different
identifier than the transmitted one, so it doesn’t accept the
message.

 Nevertheless, both receiver nodes (and all other receiver nodes in


this CAN implementation) subsequently verify and acknowledge
the data frame content to prove successful message transmission.

EEEN30024 Lecture 14 8
CAN Data Flow

Image: Renesas EEEN30024 Lecture 14 9

CAN Node Physical Interface


-typical implementation
 CAN is typically implemented using 'Dominant' (low) and 'Recessive' bits (high).

 The node produces a 'dominant' value by simultaneously driving the "C_HI" line high and
the "C_LO line" low. That is, it actively creates a positive differential voltage between
these signals.

 A 'recessive state' is created on the CAN bus whenever all nodes on the network leave
the "C_HI" and "C_LO" lines in a high-impedance state. That causes the termination
resistors to passively create a zero differential voltage between these signals.

 The CAN bus must be terminated to provide the recessive state — and to eliminate wave
reflections at ends of the bus wires. Typical DC bus terminations are in the 60-Ohm
range, and the twisted-pair cables have a 120-Ohm characteristic impedance.

signal ground wire not shown

Recessive Dominant 120 Ω CAN bus 120 Ω

C_HI C_HI
C_LO C_LO

Node A Node B

EEEN30024 Lecture 14 10
CAN Data Frame

• Notes: 29-bits for CAN 2.0B; ID extend bit allows for >2000 nodes on the bus; Rem Req
(“remote request”) for requesting the transmission of a specific identifier from another node.

Image: Renesas EEEN30024 Lecture 14 11

CAN Arbitration
Example 1:

MSB sent first

EEEN30024 Lecture 14 12
CAN Arbitration

EEEN30024 Lecture 14 13

CAN Arbitration

EEEN30024 Lecture 14 14
CAN Arbitration

EEEN30024 Lecture 14 15

CAN Arbitration

Node 3 wins

EEEN30024 Lecture 14 16
CAN Arbitration

Example 2:

recessive
Node A
dominant

Node B

Node C

bus state

Node A lost arbitration here


Node B lost arbitration here.
Node C wins arbitration

EEEN30024 Lecture 14 17

CAN Bus Arbitration

 Nodes transmit when the bus is idle

 When multiple nodes transmit simultaneously the


highest priority "wins"
 the message still gets through
 unlike Ethernet (CSMA/CD) where the
message would be lost and nodes back-off for
random periods of time

 CAN uses non-destructive CSMA/CD


 "CD" –Collision Detection- by bitwise
arbitration on the identifier field
 implies that identifiers also function as
priorities
- the lower the identifier the higher the priority
 maximum CAN utilisation ~ 100%

EEEN30024 Lecture 14 18
CAN Bus Error Checking
 Five different kinds of error checking are performed by all nodes

 message-level error checking:

 verify checksum checks


 verify a node received the message and replied with an
ACK; re-transmit if ACK not received

 bit-level error checking:

 verify that transmitted and received bits are the same (a


node listens as it transmits)

- when a node transmits dominant it always hears


dominant

- when a node transmits recessive and hears dominant


it knows there is a bus conflict

EEEN30024 Lecture 14 19

CAN Bus Error Checking


 bit-level error checking (continued):

 verify that the bit stuffing rule is respected:

- CAN uses an encoding technique called Non-return to


zero (NRZ) (discussed in detail in the next lecture)

- because there is no common clock on a CAN bus, nodes


synchronize on data transitions

- lots of consecutive zeros or ones transmitted means


fewer transitions, and this can cause a loss of
synchronization to occur (contrast with Manchester
encoding, later)

- after transmitting 5 consecutive 1’s or 0’s transmit a bit


of the opposite polarity, a technique called 'bit-stuffing'
(see next lecture); bit-stuffing is usually done at the
hardware level
EEEN30024 Lecture 14 20
CAN Clock Synchronization
 When the bus is idle nodes rapidly lose
synchronization

 an idle bus is all recessive –there are no


transitions
 bit-stuffing only applies to messages

 nodes sync to the leading edge of the SOF (“start


of frame”) bit of each new message
 additionally, nodes re-synchronize on every
recessive to dominant edge

 A fundamental requirement of CAN is that each node


on the bus must see the current bit before the next
bit is sent
 the minimum transmission time of each bit is 2 x bus
propagation delay

EEEN30024 Lecture 14 21

CAN

 Although cars commonly have multiple CAN buses, CAN is a


relatively slow medium

 it doesn’t meet all the data networking needs in an


automobile

 e.g. in-car information and entertainment (" infotainment")


requires high-speed audio and video streaming
-catered by Media-Oriented Systems Transport (MOST)
and IDB-1394b, which is based on Firewire
-Ethernet (for reasons of speed) being actively
considered

 diverse requirements mean that vehicles will generally


have to run more than one bus.

EEEN30024 Lecture 14 22
LIN
 LIN – Local Interconnect Network
 slower and low cost alternative to CAN

 single-wire (plus signal ground) bus

 speed up to 20Kbps

 single master/multiple slaves


 all messages are initiated by the master, so no arbitration
necessary and no collision detection required as at most,
one slave replies
 uses message identifiers similar to CAN
 implemented with same dominant/recessive logic

EEEN30024 Lecture 14 23

LIN
 CAN and LIN typically co-exist in automobile environments:

Image: Motorola EEEN30024 Lecture 14 24


LIN
 LIN is an automotive bus
 connects smart sensors or actuators to an ECU (Electronic
Control Unit)
 the ECU is often also a gateway to a CAN bus
 the master is typically a moderately powerful microcontroller,
whereas the slaves are less powerful, cheaper microcontrollers,
or ASICs
 slave nodes can be switched to sleep/wake-up modes

 LIN Frame:

Master sends Message Header Slave sends Message response

(to give slave time to respond)

EEEN30024 Lecture 14 25

LIN
 LIN is byte oriented
 data is sent byte at a time
 each byte field contains a start bit (dominant), 8 data bits, and a
stop bit (recessive) –similar to how a UART transmits data
 data bits are sent LSB first
 the Message Header contains a synch break that serves as a start of
frame, followed by a synch byte that serves to help the slaves
determine the time between two rising edges to determine the
Master’s transmission speed
 the ID field is one byte long, and includes parity bits; it carries the
message identifier (message type), and information about the sender
and receiver:

EEEN30024 Lecture 14 26
Lecture 15
Physical Layer:
Coding of Digital Data
Learning Outcomes :

 Be able to identify and explain the


requirements of a digital signalling code

 Identify common codes and show the signal


that results from an arbitrary binary word

 Identify the key features of common codes


and how these address the requirements

references:
 Stallings –Section 5.1, also Appendix16A

EEEN30024 Lecture 15 1

Requirements

 Transmit binary information over a digital channel


 minimise the power needed at transmitter
 provide timing information for clock recovery (often using
a Phase Locked Loop (PLL)
 reduce low frequency content
 periods of time when voltage is constant
 dc drift can cause problems
 use bandwidth efficiently
 coding should be efficient
 desirable spectral properties
 tolerance to wiring polarity mistakes

 These requirements are best explained using the


simplest form of coding NRZ
 non-return to zero level
2
EEEN30024 Lecture 15
Non-Return to Zero
(NRZ)

 Top: unipolar (0 to +Av)


 Bottom: bipolar (-A/2 to + A/2) Volts
 ‘low’ voltage = ‘1’, ‘high’ voltage = ‘0’
 follows the convention illustrated in Stallings
 which, in turn, follows the convention of data
communications interfaces
3
EEEN30024 Lecture 15

Return to Zero-Level
(RZ)
 in RZ the voltage returns to zero
 unlike NRZ, where the voltage is constant during
the bit interval

0V

 there is a bit transition during each bit interval


 requires twice the bandwidth of NRZ
 an alternative way to represent 0 is to use 0V
4
EEEN30024 Lecture 15
Power Consumption
This image cannot currently be display ed.

 Unipolar
 power is proportional to:

 Bipolar
 power is proportional to:

 The same arguments apply to other encoding schemes


discussed here.

5
EEEN30024 Lecture 15

Timing Information

 The incoming signal has to be sampled in the


middle of the bit period

 This implies that the clock at the receiver has to


be synchronised with the clock as the transmitter
 could transmit the clock over a separate line or channel
 but this is not common

 This is not a significant problem if data packets


are very short and clock can be resynchronised
each time
 Asynchronous Data Transfer

6
EEEN30024 Lecture 15
Asynchronous Data
Transfer

 Similar to RS-232. Assumes


 single start bit
 8-bit character no parity
 2 stop bits

 Receiver synchronises on each start bit

 Overhead of start and stop bits


 in this example 3/11 bits (27.3%)
7
EEEN30024 Lecture 15

Synchronous Data
Transmission
 data is transferred as block of many bits of data
 synchronisation is by clock recovery from the data
 using a phase locked loop

 this requires a steady stream of transitions


 problems arise when a long run of 1s or 0s is present in
data
 lack of transitions and synchronisation can be lost

8
EEEN30024 Lecture 15
Loss of synchronisation

 there is the potential for


 a bit to missed (shown here – slow clock at receiver)
 a bit to be sampled twice (fast clock at receiver)
 coding schemes shown later seek to address this issue

9
EEEN30024 Lecture 15

Low Frequency Content


 long streams of 1s and 0s will cause problems for receiver
clock synchronisation
 the average signal level will drift when there are long
sequences of 1s and 0s
 dc 'drift' or dc offset
 need transitions so that the signal is balanced about a central
average signal level
 this issue is often addressed in conjunction with addressing
clock synchronisation issues

10
EEEN30024 Lecture 15
Efficient use of bandwidth

 Consideration needs to be give to the relation


between the data rate and the modulation rate
–see next slide

 In NRZ the signal elements have the same


duration as the data elements
 i.e. the data rate = modulation rate

 The bandwidth required to transmit the signal


is related to the modulation rate

11
EEEN30024 Lecture 15

Data and Modulation Rate

 The data rate (or data signalling rate) is the rate


at which data is transmitted in bits per second

 The modulation rate is the rate at which the


transmitted signal changes
 this is expressed in baud, the number of signal elements
per second
 or, and perhaps more properly, the reciprocal of the
duration of the shortest signal element

12
EEEN30024 Lecture 15
Data and Modulation Rate

A. NRZ – 1 signal element per data bit period

B. Manchester (see later) – 2 signal elements per data bit


period

C. Hypothetical scheme pair of data bits transmitted as one of


4 levels, hence signal element occupies 2 data bit periods

13
EEEN30024 Lecture 15

Data and Modulation Rate

For example, assume that the data rate = 1Mbps,


thus data bit period = 1µs:

 NRZ signal element period = 1µs, thus


modulation rate = 1Mbaud

 Manchester signal element period = 0.5µs, thus


modulation rate = 2Mbaud

 Hypothetical 4-level coding, signal element period


= 2µs, thus modulation rate = 0.5Mbaud

14
EEEN30024 Lecture 15
Efficient use of coding

 In NRZ a signal element is the same duration as the data


bit period

 In the hypothetical 4-level coding scheme, the signal


element duration is twice that of the data bit period, but
because 4 levels were used, a signal element can encode a
pair of bits

 Both of these schemes are efficient from a coding point of


view since the levels used by the signal directly correspond
to data values transmitted

 Some other schemes, e.g. multilevel binary are not so


efficient
 –see later
15
EEEN30024 Lecture 15

Spectral Properties

 Reduction of high frequency components reduces


the required bandwidth
 Lack of a dc component means that ac coupling
can be used providing electrical isolation and
reducing interference
 Signal distortion and interference are related to
the spectral properties of the signal
 transmission characteristics of channels are usually
worse need the edge of bands
 thus, a signal that concentrates most of its power toward
the centre of a band will have better performance

16
EEEN30024 Lecture 15
Tolerance to
Wiring Inversion
 When complex network installations are made it
is possible for the polarity of the wires to become
reversed

 For NRZ this will lead to an inverted signal


 the 1s will become 0s and vice versa

 Differential encoding schemes, e.g. NRZI (next


slide) have the benefit that they are tolerant of
polarity inversion

17
EEEN30024 Lecture 15

Non-Return to
Zero-Invert on Ones (NRZI)

 Invert on 1s, maintain level for 0s


 NRZI is a differential encoding
 data is indicated by transitions
 tolerant to wiring polarity mistakes
 detection of transition rather than level
 Otherwise as NRZ

18
EEEN30024 Lecture 15
NRZ codes generally

 they are simple

 they make efficient use of bandwidth

 there is a potential presence of dc-component


 NRZI suffers with long zeros
 hence dc-shift and loss of synchronisation

 "unattractive for signal transmission applications"


[Stallings]
 more commonly used e.g. in digital magnetic recording

19
EEEN30024 Lecture 15

Multilevel Binary

Bipolar-AMI (Alternate Mark Inversion)


 0 no signal; 1 +ve or –ve V alternately

Pseudoternary
 1 no signal; 0 +ve and –ve alternately
20
EEEN30024 Lecture 15
Multilevel Binary
 Overall average of signal value should be 0V
 hence no dc drift
 Where long run of 1s (AMI) or 0s (pseudoternary),
transitions occur to give clock synchronisation
 however, long runs of 0s (AMI) or 1s (pseudoternary) do not
have this property and synchronisation may be lost
 however, some schemes (e.g. ISDN) insert additional bits to
force transitions
 Bandwidth is used efficiently
 Data Rate = Signal Rate
 However, the receiver has to be able to detect 3 levels
(rather than 2) in presence of noise
 compared with NRZ codes either
 increase SNR (e.g. increase power by 3dB)

 suffer greater BER for given SNR


SNR signal-to-noise ratio
BER Bit Error Rate
ISDN Integrated Services for
Digital Network 21
EEEN30024 Lecture 15

Biphase Manchester
and Differential Manchester

 Manchester
 +ve going transition for 1, -ve going transition for 0
 opposite transitions can be specified
 always a transition in the middle of the data bit

 Differential Manchester
 transition at beginning of bit for 0, no transition for 1
 always a mid-bit transition
22
EEEN30024 Lecture 15
Biphase Manchester
and Differential Manchester

 At least one transition per bit period


 clock synchronisation supported
 no dc component
 Error detection – absence of expected transition
can indicate error
 must be mid-bit transition for both forms

 Differential code is tolerant of polarity reversal

 Manchester used in some forms of IEEE802.3


(Ethernet)
 Differential Manchester used in IEEE802.5 (Token
Ring)

23
EEEN30024 Lecture 15

Biphase Manchester
and Differential Manchester

 The benefits of a biphase code are obtained at the


expense of a need for increased bandwidth
 A stream of 1s or 0s will generate 2 transitions for
each bit period
 i.e. the modulation rate is twice the data rate

 Compare a stream of 1s with the equivalent NRZI


stream
 thus for a data rate
of 10Mb/s, a signal
rate of 20Mbaud
is required

24
EEEN30024 Lecture 15
Block codes

 The idea is to combine the ability of the positive


attributes of biphase codes (like Manchester) with
a reduction in the required bandwidth

 The idea is to take a block of n data bits and


transmit m signal bits (n<m) such that the set of
m bits are chosen to maximise number of
transitions and minimise dc component
 the modulation rate is m/n x data rate

 Called nB/mB codes

25
EEEN30024 Lecture 15

Data Input Code Output

4B/5B 0000
0001
11110
01001
 Code a block of 4 bits 0010 10100
as a block of 5 bits 0011 10101
using NRZI 0100 01010
 24 = 16 data blocks, 0101 01011
possible 25 = 32 code 0110 01110
blocks 0111 01111
 Select 16 code blocks 1000 10010
with at least 2 1s 1001 10011

 because NRZI is 1010 10110

used this will force 1011 10111

2 transitions and no 1100 11010

more than 3 '0's in 1101 11011


a row 1110 11100
1111 11101

26
EEEN30024 Lecture 15
4B/5B-NRZI

 The modulation rate is 5/4 x data rate


 e.g. for 10Mbs data rate, modulation rate = 12.5MBaud
 Additional codes are used in LANs for signalling of
other conditions –for example errors.
 Other block codes are used 8B/10B in Gigabit
Ethernet, 64B/66B in 10 Gigabit Ethernet
 in each case the goal is to achieve dc balance, provide
clock synchronisation with low signal rates

27
EEEN30024 Lecture 15

Ternary block codes

 Signal element takes on one of three values:


+ve, -ve, 0
 Code n data bits into m ternary values (nB/mT)
 This achieves a modulation rate < data rate
 modulation rate is m/n x data rate
 as earlier, but m<n now

 Codes can be chosen such that transitions are


sufficiently frequent for synchronisation, and is
balanced for no dc offset
 4B/3T 16 data codes from 33 (27) possible signal codes
 8B/6T 256 data codes from 36 (729) possible signal
codes

28
EEEN30024 Lecture 15
4B3T Code

Data Output Data Output


0000 +0- (0) 1000 -++ (1) or +-- (-1)
0001 -+0 (0) 1001 ++- (1) or --+ (-1)
0010 0+- (0) 1010 +++ (3) or --- (-3)
0011 +-0 (0) 1011 +0+ (2) or -0- (-2)
0100 00+ (1) or 00- (-1) 1100 0++ (2) or 0-- (-2)
0101 0+0 (1) or 0-0 (-1) 1101 ++0 (2) or --0 (-2)
0110 +00 (1) or -00 (-1) 1110 0+- (0)
0111 +-+ (1) or -+- (-1) 1111 -0+ (0)
29
EEEN30024 Lecture 15

4B3T Code

 The algorithm keeps track of the cumulative dc


balance

 Codes may be inverted (see previous slide)


where codes have a next positive dc balance

 Overall aim of the code is to maintain the dc


balance, provide sufficient transitions for clock
synchronisation (much better in 8B6T) and to
minimise the modulation rate requirement
30
EEEN30024 Lecture 15
Scrambling
Techniques

 Biphase techniques used up to 10Mbps but not


widely used in long distance applications because
of the high signalling rate

 Scrambling systems have been developed that


‘violate’ code sequences of simple codes such as
Bipolar-AMI to give:
 no dc component
 no long sequences of zero-level signals
 no reduction of data rate (or increase in modulation rate)
 error detection capabilities

31
EEEN30024 Lecture 15

Scrambling
Techniques

 B8ZS – bipolar with 8-zeros substitution


 insert a code violation for run of 8 zeros

 HDB3 – high density bipolar-3 zeros


 replace string of 4 zeros with code violation

32
EEEN30024 Lecture 15
B8ZS

 Based on bipolar-AMI
 removes the case where there are long sequences of
zeros

 When a run of 8 zeros is found substitute with


 000+-0-+ if the last voltage pulse was positive
 the first + and the second – are code violations
 000-+0+- if the last voltage pulse was negative
 the first – and the second + are code violations

33
EEEN30024 Lecture 15

HDB3
 Based on bipolar-AMI
 addresses the issues associated with runs of zeros

 For a sequence of 4 zeros, use the following


replacements
 note the substitution is dependent on the polarity of the
preceding pulse and the number of ones since the last
substitution and the last bit in the sequence of 4 is a
code violation

Polarity of preceding Odd number of pulses Even number of pulses


pulse since last substitution since last substitution
- 000- +00+
+ 000+ -00-

34
EEEN30024 Lecture 15
Appendix: (examinable)
Construction of Frames
 A frame 'start' and 'end' must be marked

 Four basic techniques will be briefly discussed:

 Character count
 Flag bytes with byte stuffing
 Starting and end flags with bit stuffing
 Physical layer coding violations

35
EEEN30024 Lecture 15

Character Count
 Include a field in the frame that contains the
number of characters to be found

 Errors introduced into the character count can


cause errors at the frame level
 see next slide

 Error checking can detect errors, but because


synchronisation is lost, the destination can no
longer identify frame boundaries and know which
frames require retransmission

 Rarely used on their own, but often used in


combination with other approaches to verify the
validity of a frame
36
EEEN30024 Lecture 15
Single Bit Error
in Count Field
 Assumes simple frames (no header other than
count and no trailer)

 Assumes first character treated as count and


others as ASCII

37
EEEN30024 Lecture 15

Single Bit Error


in Count Field
 Assumes simple frames (no header other than
count and no trailer)

 Assumes first character treated as count and


others as ASCII

Example Frame

ESC T E S T ESC

6 H E L L O

Frame 1

38
EEEN30024 Lecture 15
Flag Bytes with Byte Stuffing
 Use a ‘special byte’ (a flag byte) to mark the
start and of frames
 for example the byte 01111110 may be used
 In binary data the flag byte may occur
 prefix the flag byte in the data with a special escape byte
(ESC)
 thus flag byte in data is two bytes ESC-FLAG
 in binary data the ESC byte may occur, when it does
prefix with the ESC byte
 thus ESC byte in data is given by ESC-ESC
 The use of the ESC byte gives rise to the term ‘byte
stuffing’
 Approach used in PPP (Point-to-Point Protocol)

39
EEEN30024 Lecture 15

Byte Stuffing

40
EEEN30024 Lecture 15
Bit Stuffing
 A flag byte is used to mark the start and end of
frames as in byte stuffing
 say the 01111110 we used earlier

 When this pattern appears in the data rather


than prefix with an ESC byte, a 0 bit is inserted
after the 5th 1 in a sequence
 Whenever the pattern 111110 is found in the
data it is replaced at the receiving end by the
pattern 11111
 Receiver can always find frame boundary – run of
6 1's
 Allows arbitrary bit patterns to be inserted into
data
 this property is called data transparency

41
EEEN30024 Lecture 15

Bit Stuffing Example

42
EEEN30024 Lecture 15
Physical Layer Coding
Violations
 Can use code violations or additional codes to
signal frame ends in physical coding systems that
use more than 1 signal bit

 For example
 Manchester coding requires a transition in the middle of
the data bit, a data bit with no transition could be used
to signal frame end
 in 4B/5B coding there are 32 code, only 16 of which are
used to transmit data, other codes can be used to mark
frame boundaries

43
EEEN30024 Lecture 15
Lecture 16
Wireless Networks
Learning Outcomes :

 Be able to explain the characteristics of


wireless networks

 IEEE 802.11

 IEEE 802.15

references:
 Reading: K&R Chapter 6

EEEN30024 Lecture 16 1

Elements of a
wireless network

network
infrastructure

EEEN30024 Lecture 16 2
Elements of a
wireless network

wireless hosts
 laptop, smartphone
 run applications
 may be stationary
network (non-mobile) or mobile
infrastructure  wireless does not
always mean mobility

EEEN30024 Lecture 16 3

Elements of a
wireless network

base station
 typically connected to
wired network
 relay - responsible for
sending packets
network between wired
infrastructure network and wireless
host(s) in its “area”
 e.g., cell towers,
802.11 access points

EEEN30024 Lecture 16 4
Elements of a
wireless network

wireless link
 typically used to connect
mobile(s) to base station
 also used as backbone
link
network  multiple access protocol
coordinates link access
infrastructure
 various data rates,
transmission distance

EEEN30024 Lecture 16 5

Characteristics of
selected wireless links

200 802.11n

54 802.11a,g 802.11a,g point-to-point


Data rate (Mbps)

5-11 802.11b 4G/LTE /WIMAX

4 3G: UMTS/WCDMA-HSPDA, CDMA2000-1xEVDO

1 802.15

.384 2.5G: UMTS/WCDMA, CDMA2000

.056 2G: IS-95, CDMA, GSM

Indoor Outdoor Mid-range Long-range


10-30m 50-200m outdoor outdoor
200m – 4 Km 5Km – 20 Km

EEEN30024 Lecture 16 6
Elements of a
wireless network

infrastructure mode
 base station connects
mobiles into wired
network
 network provides the
network traditional services of
infrastructure addressing and
routing

EEEN30024 Lecture 16 7

Elements of a
wireless network

ad hoc mode
 no base stations
 nodes can only
transmit to other
nodes within link
coverage
 nodes organize
themselves into a
network: route
among themselves

EEEN30024 Lecture 16 8
Wireless Network Taxonomy

single hop multiple hops

host connects to host may have to


infrastructure base station (WiFi, relay through several
WiMAX, cellular) wireless nodes to
(e.g., APs)
which connects to connect to larger
larger Internet
Internet: mesh net

no base station, no
connection to larger
no no base station, no Internet. May have to
connection to larger
infrastructure relay to reach other
Internet (Bluetooth, a given wireless node
ad hoc nets) MANET, VANET

EEEN30024 Lecture 16 9

Wireless
Link Characteristics (1)
important differences from wired link ….

 decreased signal strength: radio signal attenuates as it


propagates through matter (path loss)

 interference from other sources: standardized wireless


network frequencies (e.g., 2.4 GHz) shared by other devices
(e.g., phone); devices (motors) interfere as well

 multipath propagation: radio signal reflects off objects


ground, arriving at destination at slightly different times

…. make communication across (even a point to point) wireless link


more difficult

EEEN30024 Lecture 16 10
Wireless
Link Characteristics (2)
 SNR: signal-to-noise ratio 10-1

 larger SNR – easier to extract 10-2


signal from noise (a “good
thing”) 10-3

 SNR versus BER tradeoffs

BER
10-4
 given physical layer: increase
power -> increase SNR- 10-5

>decrease BER
10-6
 given SNR: choose physical
layer that meets BER 10-7
requirement, giving highest 10 20 30 40
SNR(dB)
thruput
• SNR may change with QAM256 (8 Mbps)
mobility: dynamically adapt
physical layer (modulation QAM16 (4 Mbps)
technique, rate)
BPSK (1 Mbps)

EEEN30024 Lecture 16 11

Wireless
Network Characteristics
Multiple wireless senders and receivers create additional
problems (beyond multiple access):

A B C
C

A’s signal C’s signal


B strength strength
A

Hidden terminal problem


space

 B, A hear each other Signal attenuation:


 B, C hear each other  B, A hear each other
 A, C can not hear each other  B, C hear each other
means A, C unaware of their  A, C can not hear each other
interference at B interfering at B

EEEN30024 Lecture 16 12
Code Division Multiple Access
(CDMA)

 A unique “code” is assigned to each user; i.e., code set


partitioning

 all users share same frequency, but each user has own
“chipping” sequence (i.e., code) to encode data
 allows multiple users to “coexist” and transmit
simultaneously with minimal interference (if codes are
“orthogonal”)

 encoded signal = (original data) X (chipping sequence)

 decoding: inner-product of encoded signal and chipping


sequence

EEEN30024 Lecture 16 13

CDMA encode/decode

channel output Zi,m


Zi,m= di.cm
data d0 = 1
1 1 1 1 1 1 1 1
d1 = -1
bits -1 -1 -1 -1 -1 -1 -1 -1
sender
1 1 1 1 1 1 1 1 slot 1 slot 0
code channel channel
-1 -1 -1 -1 -1 -1 -1 -1
output output
slot 1 slot 0

M
Di =  Zi,m.cm
m=1
M
received 1 1 1 1 1 1 1 1
d0 = 1
-1 -1 -1 -1 -1 -1 -1 -1
input d1 = -1

1 1 1 1 1 1 1 1 slot 1 slot 0
code channel channel
-1 -1 -1 -1 -1 -1 -1 -1

receiver output output


slot 1 slot 0

EEEN30024 Lecture 16 14
CDMA:
two-sender interference
channel sums
together
transmissions by
Sender 1 sender 1 and 2

Sender 2

using same code as


sender 1, receiver
recovers sender 1’s
original data from
summed channel
data!

EEEN30024 Lecture 16 15

IEEE 802.11
Wireless LAN
802.11b 802.11a
 2.4-5 GHz unlicensed spectrum  5-6 GHz range
 up to 11 Mbps  up to 54 Mbps
 direct sequence spread 802.11g
spectrum (DSSS) in physical  2.4-5 GHz range
layer  up to 54 Mbps
 all hosts use same chipping 802.11n: multiple antennae
code  2.4-5 GHz range
 up to 200 Mbps

 all use CSMA/CA for multiple access


 all have base-station and ad-hoc network versions

EEEN30024 Lecture 16 16
802.11
LAN Architecture
 wireless host
communicates with base
Internet station
 base station = access
point (AP)
 Basic Service Set (BSS)
hub, switch (aka “cell”) in
or router infrastructure mode
contains:
 wireless hosts
 access point (AP): base
BSS 1
station
 ad hoc mode: hosts only

BSS 2
EEEN30024 Lecture 16 17

802.11:
Channels, Association

 802.11b: 2.4GHz-2.485GHz spectrum divided into 11


channels at different frequencies
 AP admin chooses frequency for AP
 interference possible: channel can be same as that chosen
by neighboring AP!

 host: must associate with an AP


 scans channels, listening for beacon frames containing
AP’s name (SSID) and MAC address
 selects AP to associate with
 may perform authentication
 will typically run DHCP to get IP address in AP’s subnet

EEEN30024 Lecture 16 18
802.11:
Passive/Active Scanning
BSS 1 BSS 2 BSS 1 BSS 2

1
1 1 2 2 AP 2
AP 1 AP 2 AP 1
2 3
3 4

H1 H1

passive scanning: active scanning:


(1)beacon frames sent from APs (1) Probe Request frame broadcast
(2)association Request frame from H1
sent: H1 to selected AP (2) Probe Response frames sent
(3)association Response frame from APs
sent from selected AP to H1 (3) Association Request frame sent:
H1 to selected AP
(4) Association Response frame sent
from selected AP to H1
EEEN30024 Lecture 16 19

IEEE 802.11:
Multiple Access
 avoid collisions: 2+ nodes transmitting at same time
 802.11: CSMA - sense before transmitting
 don’t collide with ongoing transmission by other node
 802.11: no collision detection!
 difficult to receive (sense collisions) when transmitting due to
weak received signals (fading)
 can’t sense all collisions in any case: hidden terminal, fading
 goal: avoid collisions: CSMA/C(ollision)A(voidance)

A B C
C

A’s signal C’s signal


B strength
A strength

space

EEEN30024 Lecture 16 20
IEEE 802.11 MAC Protocol:
CSMA/CA
802.11 sender
1 if sense channel idle for DIFS then sender receiver
transmit entire frame (no CD)
2 if sense channel busy then DIFS
start random backoff time
timer counts down while channel idle
data
transmit when timer expires
if no ACK, increase random backoff interval,
repeat 2 SIFS

802.11 receiver ACK


- if frame received OK
return ACK after SIFS (ACK needed due to
hidden terminal problem)

EEEN30024 Lecture 16 21

Avoiding Collisions (more)

idea: allow sender to “reserve” channel rather than


random access of data frames: avoid collisions of long
data frames

 sender first transmits small request-to-send (RTS)


packets to BS using CSMA
 RTSs may still collide with each other (but they’re short)
 BS broadcasts clear-to-send CTS in response to RTS
 CTS heard by all nodes
 sender transmits data frame
 other stations defer transmissions

avoid data frame collisions completely


using small reservation packets!

EEEN30024 Lecture 16 22
Collision Avoidance: RTS-CTS exchange
A B
AP

Timeout reservation collision

SIFS

SIFS

DATA (A)
B
defers

time SIFS

EEEN30024 Lecture 16 23

802.11 Frame: addressing

2 2 6 6 6 2 6 0 - 2312 4
frame address address address seq address
duration payload CRC
control 1 2 3 control 4

Address 4: used
only in ad hoc mode
Address 1: MAC address
of wireless host or AP Address 3: MAC address
to receive this frame of router interface to which
AP is attached
Address 2: MAC address
of wireless host or AP
transmitting this frame

EEEN30024 Lecture 16 24
802.11 Frame: addressing

Internet
H1 R1 router

R1 MAC addr H1 MAC addr


dest. address source address

802.3 frame

AP MAC addr H1 MAC addr R1 MAC addr

address 1 address 2 address 3

802.11 frame

EEEN30024 Lecture 16 25

802.11 Frame: more


frame seq #
duration of reserved
(for RDT)
transmission time (RTS/CTS)

2 2 6 6 6 2 6 0 - 2312 4
frame address address address seq address
duration payload CRC
control 1 2 3 control 4

2 2 4 1 1 1 1 1 1 1 1
Protocol To From More Power More
Type Subtype Retry WEP Rsvd
version AP AP frag mgt data

frame type
(RTS, CTS, ACK, data)

EEEN30024 Lecture 16 26
802.11:
Mobility Within Same Subnet
 H1 remains in same IP
subnet: IP address can
remain same

 switch: which AP is
associated with H1?
 self-learning: switch
will see frame from H1
and “remember” which
switch port can be used BSS 1 H1 BSS 2
to reach H1

EEEN30024 Lecture 16 27

802.11:
Advanced Capabilities
Rate adaptation
10-1

10-2
 base station, mobile 10-3
dynamically change
BER

10-4
transmission rate (physical
layer modulation 10-5

technique) as mobile 10-6

moves, SNR varies 10-7


10 20 30 40
SNR(dB)

1. SNR decreases, BER


QAM256 (8 Mbps)
QAM16 (4 Mbps) increase as node moves
BPSK (1 Mbps) away from base station
operating point

2. When BER becomes too


high, switch to lower
transmission rate but with
lower BER

EEEN30024 Lecture 16 28
802.11:
Advanced Capabilities

power management

 node-to-AP: “I am going to sleep until next beacon


frame”
 AP knows not to transmit frames to this node
 node wakes up before next beacon frame

 beacon frame: contains list of mobiles with AP-to-


mobile frames waiting to be sent
 node will stay awake if AP-to-mobile frames to be sent;
otherwise sleep again until next beacon frame

EEEN30024 Lecture 16 29

802.15:
Personal Area Network

 less than 10 m diameter


 replacement for cables P
S
(mouse, keyboard,
headphones) P
radius of
M
 ad hoc: no infrastructure coverage

 master/slaves: P
S S
 slaves request permission to P
send (to master)
 master grants requests
 802.15: evolved from
M Master device
Bluetooth specification
 2.4-2.5 GHz radio band S Slave device
 up to 721 kbps P Parked device (inactive)

EEEN30024 Lecture 16 30
Chapter 6 summary

Wireless

 wireless links:
 capacity, distance
 channel impairments
 CDMA

 IEEE 802.11 (“Wi-Fi”)


 CSMA/CA reflects wireless channel
characteristics

 IEEE 802.15
 Personal Area Networks

EEEN30024 Lecture 16 31

Appendix: (examinable)
MAC – Coordination function
 This is the mechanism that controls access to the wireless
medium within a BSS
 Ethernet would use CSMA/CD for this purpose

 However, a wireless system cannot use collision detection


(therefore no CD)
 Variations in signal strength are large
 Many radio systems do not support concurrent listen
and transmit operations

 The technique used is a type of CSMA algorithm


 So the carrier is sensed, but this poses some problems

EEEN30024 Lecture 16 32
IEEE 802.11 MAC Coordination
 2 Modes
 DCF (Distributed Coordination Function)
 Basic operation has been described earlier
 CTS-RTS
 Distributed in the sense that all stations take part
 like Ethernet
 PCF (Point Coordination Function)
 Managed by Access Point (Base Station) for BSS
(cell)
 Contention-free system based on polling
 Built on top of DCF
 DCF and PCF can work together
 PCF for time critical services
EEEN30024 Lecture 16 33

DCF at non-participating
stations

 When a station hears an RTS or CTS the


station will refrain from transmitting on that
virtual channel for the period specified by the
RTS or CTS.

EEEN30024 Lecture 16 34
DCF Issues (1)

 Collisions can occur


 When two parties send an RTS at the same
time
 Collision is detected by the fact that no CTS
is received
• time out
 RTS can be re-tried
• Using an exponential backoff algorithm (such as
Ethernet)

EEEN30024 Lecture 16 35

DCF Issues (2)

 Errors can occur in frames


 This is also true of Ethernet and these are
recovered at higher protocol levels
• generally the Transport Layer.
 But errors are more prevalent in wireless
system.
 Therefore, recover from errors at MAC level
 achieved by the use of the ACK frame that informs
the sender that the frame has been successfully
received.
 Non reception of ACK leads to error and
process restarting.

EEEN30024 Lecture 16 36
Errors
 Wireless networks are more prone to error at the
physical level than a wired network.

 If the probability of a bit being in error is p, the


probability of an n-bit frame being in error is
 (1-p)n
 Thus, the longer the frame the greater the
probability of error.

 Stallings notes that the probability of an standard


Ethernet frame
 1518 bytes (12,144 bits) being received correctly is:
0.297 for p = 10-4, 0.886 for p = 10-5 and 0.987 for p = 10-6

EEEN30024 Lecture 16 37

Errors

EEEN30024 Lecture 16 38
Reducing retransmissions
due to bit errors
 If a frame is split into smaller fragments
 each one being separately acknowledged.
The number of retransmissions is reduced at the
expense of additional bandwidth requirements to
transmit the acknowledgements
 Each fragment has its own checksum
 each fragment has a sequence number
 a stop and wait protocol is used – i.e. wait for
acknowledgement.
 There also has to be a mechanism to ensure that
other stations do not collide with the transmissions
 This is handled by the way in which the Interframe
Spacing is specified – see later.
 The mechanism allows repeated fragments to be sent
without an new RTS/CTS handshake taking place.
EEEN30024 Lecture 16 39

Reducing retransmissions
due to bit errors - example

EEEN30024 Lecture 16 40
PCF
 This is a contention-free algorithm managed
by a base station (access point)
 The base station periodically sends a Beacon
Frame (10 to 100 times per second)
 this broadcasts various system parameters
 allows stations to sign up for the PCF service.
 The base station will periodically poll stations
signed up for the service and accept their
frames.
 The algorithm supports stations that have
time-critical requirements.
 It can cause stations to sleep – thus saving
power.
 PCF can coexist with DCF.

EEEN30024 Lecture 16 41

Interframe Spaces

 There are specified time gaps between the end


of one transmission and the next.
 There are four gaps and these allow the DCF
and PCF protocols to co-exist and also support
fragmentation.

EEEN30024 Lecture 16 42
Interframe Spacing

 The timing provides a priority scheme.


 Frames that can be sent in SIFS have a higher
priority than PIFS etc.

EEEN30024 Lecture 16 43

Interframe Spacing

 SIFS - Short Interframe Spacing


 Only one station can operate in this period
 The following frames can be sent
• ACK (in response to a data frame or fragment)
• CTS (in response to an RTS)
• A data frame or fragment (following a CTS)
• A fragment (following from the acknowledgement
of an earlier fragment)
• The response by a station polled under PCF

EEEN30024 Lecture 16 44
Interframe Spacing
 PIFS - Point coordination Interframe Spacing
 A beacon frame or the polling of a station by the
base station.
 Has higher priority than contention-based traffic.
 Polling needs to organised so that it does not freeze
out the contention-based traffic
• a 'Superframe' is used with all polling taking place
at the beginning of the 'Superframe'.
 DIFS – DCF Interframe Spacing
 RTS, operated under the DCF algorithm given earlier
 uses exponential backoff in the face of collisions.
 EIFS – Extended Interframe Spacing
 reports bad or unknown frames.

EEEN30024 Lecture 16 45
Lecture 17:
Network Security 1
Introduction
Symmetric Key Encryption
Learning Outcomes :
Be able to
 Identify and explain the key network security
requirements, principles and assumptions
 Explain symmetric-key encoding algorithms

 Giving an overview of the DES and AES


algorithms
 Give examples of operation of their basic
tools
references:
 Kurose and Ross chapter 8

1
EEEN30024 - Data Networking - Lecture 17

Network Security
Requirements
 Confidentiality (Secrecy)
 keep information out of the hands of unauthorised 3rd
parties
 Integrity
 ensure that data is not modified by unauthorised 3rd
parties
 Authenticity
 Ensure the identify of a party
 they actually are who they say they are

 Non-repudiation
 ensure that having sent a message the sender cannot
subsequently deny having sent it

2
EEEN30024 - Data Networking - Lecture 17
Confidentiality
with Encryption

Alice and Bob are


the principals
 Symmetric Encryption KA=KB
 Asymmetric Encryption KA ≠ KB

 In both cases,
3
EEEN30024 - Data Networking - Lecture 17

Types of attack

 Passive (by Eve the eavesdropper)


 Listens to messages
 May undertake traffic analysis to determine significant
patterns
 Difficult to detect

 Active (by Trudy the intruder)


 Masquerades as one of the principals or another entity
(e.g. DNS server – see Lecture 18)
 Replays messages sent by a principal or other entity
 Modifies messages
 Interferes with normal network operation
 e.g. Denial of Service attack
 e.g. TCP SYN attack
 Easier to detect than Eve

4
EEEN30024 - Data Networking - Lecture 17
Principles and Assumptions (1)
 Algorithm is known to the attacker, only the key
is secret
 principle first stated by Kerckhoffs
-assume the encryption system is secure even if it
knowledge of how it works is available

 Long keys should be used to increase the work


factor for the attacker
 Consider as an analogy a mechanical combination lock
 number of combinations to unlock is 10n

 where n = number of digits

5
EEEN30024 - Data Networking - Lecture 17

Principles and Assumptions (2)


 Attacker may have access to
 Ciphertext only

 Some ciphertext matched with plaintext


 because the attacker can make a reasonable guess as
to the contents of parts of the message

 A system that allows the attacker to encrypt


plaintext of her choosing using the encryption
algorithm
 Of course she doesn’t have the key

6
EEEN30024 - Data Networking - Lecture 17
Cryptosystems and keys
 There are two fundamental types of
cryptographic key encryption/decryption
systems.
 Those that use a shared secret key –based on the use of
‘symmetric key’ algorithms.
 Those that avoid the sharing of secret keys –based on
the use of ‘asymmetric key’ algorithms.
 Some protocols either use one or the other of these
types, for example computer login account verification.

 Some protocols use both types


 for example Secure Sockets Layer (SSL), Transport
Layer Security (TLS), Secure SHell (SSH).

7
EEEN30024 - Data Networking - Lecture 17

Symmetric-key
Algorithms
 Use the same key for encryption and decryption
 Alice and Bob must have the same key

 Usually a block cipher, where a fixed-size


plaintext block is sent as the same-sized
ciphertext block
 block sizes of 64 to 256 bits are common

 Symmetric-key algorithms use a combination of


scrambling techniques (bit manipulations) and
XOR operations with parts of the key

8
EEEN30024 - Data Networking - Lecture 17
Basic Tools: XOR with Key

 Symmetric-key algorithms work by XORing parts


of the key with parts of the plaintext to produce
the ciphertext

 XOR has the property that


 P=K  (P  K)

 A simple system might allow Alice to XOR her


plaintext with the key and Bob to decrypt using
the same operation

9
EEEN30024 - Data Networking - Lecture 17

Basic Tools: XOR with Key


Example
 Suppose working in 8-bit blocks
 If K = 01110001 and P = 01011100
then P  K = 01011100 
01110001
00101101 – sent by Alice

 K  (P  K) = 01110001 
00101101
01011100 – recovered by Bob

 In this example, Eve has to try only 28 keys

10
EEEN30024 - Data Networking - Lecture 17
Basic Tools: Bit Scrambling

P-Box S-Box Product cipher


Transposes Substitutes Scrambles bits using a
bits one symbol combination of P and S boxes
for another
In this example, the 12 input
In this case bits emerge scrambled
3-bit
symbols

11
EEEN30024 - Data Networking - Lecture 17

Symmetric–Key Algorithms
with XOR and bit scrambling
 To provide a complex encoding several rounds
are used

 Each round consists of a set of scrambling


operations and some element derived from some
of the key being XORed with the scrambled data.

 The next slide shows a very simple example


using 8-bit data block and 16-bit key
 plaintext = 10110111
 key = 1010101000001111 applied in two parts
 least significant word applied first in example
 S simply inverts bits – to make example simpler
 two rounds used
12
EEEN30024 - Data Networking - Lecture 17
Simple Example

13
EEEN30024 - Data Networking - Lecture 17

Data Encryption Standard


(DES)
 Uses 64-bit plaintext blocks to give 64-bit
ciphertext blocks
 A 56-bit key is used
 Too small, DES is now insecure
 Has 19 rounds
 round 1 permutes (scrambles) the plaintext bits
 independent of key

 rounds 2 to 17 apply functions to the plaintext


parameterised by the key
 round 18 exchanges the two 32-bit halves of the word
 round 19 inverse of Round 1

14
EEEN30024 - Data Networking - Lecture 17
DES Stages [2]

15
EEEN30024 - Data Networking - Lecture 17

Rounds

 64-bit block split


into two halves
 left Li-1 and right Ri-1,
where i is the round
number
 Ri-1 becomes Li
 Ri = Li-1  F(Ri-1, Ki)
 Ki is 48 bits selected
from the key
 Different selection for
each round

16
EEEN30024 - Data Networking - Lecture 17
Round

17
EEEN30024 - Data Networking - Lecture 17

DES
 DES has a 56-bit key (for political reasons)
 DES has been broken
 the key can be found within one day – 7.2x1016 keys
 DES is relatively quick
 Triple DES is used, this applies the algorithm three
times
 can use two keys
 112 bits believed to be adequate – 5.2x1033 keys
 if K1 = K2, compatible with single DES
 can use 3 keys (168 bits – 3.7 x 1050)

18
EEEN30024 - Data Networking - Lecture 17
Advanced Encryption Standard
(AES)

 AES is the successor to DES


 Supports key lengths of 128 and 256 bits with a
128-bit block
 Description given here assumes 128-bit key
 Again the algorithm has a number of rounds, at
each round the data is scrambled and part of the
key is XORed with the data

19
EEEN30024 - Data Networking - Lecture 17

AES Algorithm

Ciphertext

20
EEEN30024 - Data Networking - Lecture 17
AES Algorithm

 The 128-bit plaintext is placed into a 4x4 byte


array
 data is arranged into columns
 1st 4 bytes in 1st column

 this array is known as the state and it is operated on in


each stage of the algorithm

 The 128-bit key is expanded into 11 4x4 byte


arrays (RK0 to RK10)
 a complex set of rotation and XORing operations are
required to produce the 11 round keys

21
EEEN30024 - Data Networking - Lecture 17

AES Algorithm
 The initial step is to XOR RK0 with the state
before the rounds start

 Each round (except Round 10) has 4 steps


 an S-box is used to substitute each of the bytes in the
state
 rotate each row to the left
 row 0 by 0 bytes, Row 1 by 1 byte, Row 2 by 2 bytes,
row 3 by 3 bytes
 mix columns
 the columns are mixed using a matrix multiplication
using a finite Galois field
 the columns are mixed independently of each other
 XOR round key with state

22
EEEN30024 - Data Networking - Lecture 17
AES Algorithm

 Decoding can be carried out by repeating


the encryption process with different
tables

 The algorithm is complex, but has good


performance

23
EEEN30024 - Data Networking - Lecture 17

Symmetric-Key
Algorithms
 In effect, a symmetric key algorithm simply substitutes one
block of plaintext for another block of ciphertext.

 The substitution of the plaintext block for the ciphertext


block is dependent on the key.

 The same plaintext block always results in the same


ciphertext block for a given key.

 This property can make the algorithms subject to attack.

 In order to remove this property a number of techniques


can be used
 we’ll look at one – Cipher Block Chaining
 note that this also applies to the asymmetric-algorithm
RSA discussed in the next lecture

24
EEEN30024 - Data Networking - Lecture 17
Cipher Block Chaining
 The idea is to XOR each plaintext block with the
preceding ciphertext block before it is encrypted.

 The first plaintext block is XORed with a random


Initialisation Vector (IV), which is transmitted
(in plaintext).

 The process is shown on the following slide..

25
EEEN30024 - Data Networking - Lecture 17

Cipher Block Chaining

26
EEEN30024 - Data Networking - Lecture 17
Symmetric-Key Algorithms
Asymmetric-Key Algorithms

 The major problem with symmetric-key


algorithms is the key distribution problem.
 How do both Alice and Bob get hold of the key
without directly using the untrustworthy
network?
 this issue is explored in Lecture 18

 An alternative approach is to use an asymmetric-


key algorithm.
 In this case each party has two keys
 a public key, which Alice publishes
 a private key, which Alice uses to decode ciphertext
encoded with the public key
 see next lecture

27
EEEN30024 - Data Networking - Lecture 17
Lecture 18:
Network Security 2
Asymmetric Key Encryption
Digital Signatures
Learning Outcomes :
Be able to
 Explain and use the RSA algorithm with small values of n
 Explain how digital signatures are used
 Identify the ways in which digital signatures can be created
and how they protect data
 Describe the methods by which message digests can be
used to provide digital signatures
 Explain how the ‘birthday attack’ can be used to generate 2
messages with the same one-way hash function result
 references:
 Kurose and Ross chapter 8

EEEN30024 - Data Networking - Lecture 18 1

Asymmetric-Key Algorithms
 Considered from Alice’s perspective she has two
keys
 EA, which is her public key used by people who wish to
communicate with her to encode plaintext
 DA, which is her private key which she uses on the cipher
text to decipher a message encoded with EA

 Thus
 P = DA(EA(P))
 determining DA from EA must be very difficult, since EA is
public
 the ciphertext cannot be decrypted
 Eve can have access to the encryption algorithm and
Alice’s public key

EEEN30024 - Data Networking - Lecture 18 2


RSA
 RSA (Rivest, Shamir, Adelman) is a widely used
asymmetric-key algorithm

 It is very secure

 It uses a large (1024-bit) key


 compared with 128-bit or 256-bit for AES,
which makes RSA relatively slow

EEEN30024 - Data Networking - Lecture 18 3

RSA approach
- preliminaries
 Two large prime numbers (p and q) are chosen
 large = 512 bits

 Calculate
 n = p x q and z = (p - 1) x (q – 1)

 Choose a number that is relatively prime to z


 this is e
 ‘Relatively prime to z’ means that e does not share
common factors with z

 Find d such that (e x d) mod z = 1

EEEN30024 - Data Networking - Lecture 18 4


RSA approach - encryption
 Divide plaintext into blocks
 This must be done so the ‘value’ of the plaintext (M) is
in the range 0 ≤ M < n
 This can be achieved by using block of k bits, where k is
largest integer for n > 2k
 Encrypt a message M use C = Me(mod n)
 To decrypt a message M = Cd(mod n)
 Thus e and n are needed to encrypt, these are
the public key
 And d and n are needed to decrypt, the private
key

EEEN30024 - Data Networking - Lecture 18 5

RSA
 RSA may not seem that secure
 if z and e are known the attacker can use Euclid’s algorithm
to get d
 since e is known (part of public key) the attacker needs
only z

 but to get z the attacker needs p and q, these are primes


and factors of n, which is known (part of the public key)
 therefore ‘all’ the attacker has to do is to factorise n into p
and q
 this is a very difficult problem
 the only known solution is brute force, this is estimated
to take 1025 years on a machine with a 1µs instruction
time

EEEN30024 - Data Networking - Lecture 18 6


RSA simplified example

 Alice chooses p and q, p = 17 and q = 13


 These must be primes and Alice must keep
them secret
 Alice computes n = p x q = 17 x 13 = 221 and z
= (p – 1)(q – 1) = 16 x 12 = 192
 Alice chooses e to be relatively prime to z,
suppose e is chosen to be 5
 Alice has now produced her public key
 (n, e) (221, 5)

EEEN30024 - Data Networking - Lecture 18 7

RSA simplified example


 Alice also needs to construct her private key (n, d)
 n is known and d is given by
 e x d = 1 (mod z)
 This can be calculated using the Extended Euclidian
Algorithm
 In this case we will use trial and error to determine the
value
 We want e x d (mod z) = 1, 5 x d (mod 192) = 1
 Note that y x 192 + 1, (where y is an integer) will give
an modulo division value of 1
 i.e. 193, 385, 577 etc
 We need an integer value for d, this is achieved when d
= 77
 Since 5 x 77 = 385
 Alice now has her private key (221, 77)

EEEN30024 - Data Networking - Lecture 18 8


RSA simplified example

 Bob now uses the public key to encrypt the


message, suppose that he will send the ASCII
character ‘B’, it’s value is 66
 The ciphertext is produced by C = Me(mod n)
 Thus C = 665(mod 221), this gives 53 and this is
the ciphertext message sent by Bob

EEEN30024 - Data Networking - Lecture 18 9

RSA simplified example

 Alice now decrypts using


 her private key (n, d) (221,
77)
 and M = Cd(mod n)

 thus M = 5377(mod 221) = 66


 the message sent by Bob

EEEN30024 - Data Networking - Lecture 18 10


RSA
 In the example, with n = 221, we are
restricted to 7-bit characters for each
message
 In practice p and q are chosen so the they
are around 512 bits, giving an n of around
1024 bits, thus a block can be 1024 bits
 Larger than DES or AES
 Some form of chaining may be required as
with symmetric-key algorithms
 RSA is very slow compared with symmetric-
key algorithms and generally used as a
means of encrypting one-time session keys
for use with a symmetric-key algorithm
EEEN30024 - Data Networking - Lecture 18 11

Digital Signatures

 Verification of sender
 Alice sent the message (not Trudy)
 Message cannot be repudiated
 Alice cannot deny that she sent the message
 Message cannot be altered nor concocted
 Bob/Trudy cannot construct the message and pretend
Alice sent it
 Look at 3 techniques
 Symmetric-key cryptography with a Trusted Central
Agency
 Asymmetric-key cryptography
 Message Digests with asymmetric-key cryptography for
signing

EEEN30024 - Data Networking - Lecture 18 12


Symmetric-key
cryptography with a Trusted
Central Agency
A, KA(B, RA, t ,P) KB(A, RA, t, P, KCTA(A, t, P))
Alice CTA Bob

 A = Alice  KB = Bob’s key


 KA = Alice’s Key  known only to Bob and
 known only to Alice and CTA
CTA  KCTA = CTA’s key
 B = Bob  known only to CTA
 RA = Random Number
generated by Alice
 t = time
 P = Plaintext

 CTA = Central Trusted


Agency
EEEN30024 - Data Networking - Lecture 18 13

Symmetric-key
cryptography with a Trusted
Central Agency
 CTA must be trusted, if so
 Verification of sender
 CTA can verify Alice because of the use of her key, Bob
trusts CTA to say it’s Alice and CTA does so in a message
encrypted with Bob’s key
 Message cannot be repudiated
 Bob keeps KCTA(A, t, P), which can be verified by CTA if
dispute arises
 Message cannot be altered nor concocted
 Bob cannot create KCTA(A, t, P)
 Trudy cannot encode the CTA’s message to Bob because
she does not know KB

EEEN30024 - Data Networking - Lecture 18 14


Asymmetric-key
cryptography
Alice Bob
Plaintext EB(DA(P)) Plaintext
DA EB DB EA

DA(P)

 D = Private Key  Bob decodes to get


 E = Public Key Plaintext, but also keeps
DA(P)
 Requires both
 D(E(P))=P (normal)
 E(D(P))=P
 RSA and other
asymmetric-key codes
have this property

EEEN30024 - Data Networking - Lecture 18 15

Asymmetric-key
cryptography

 Verification of sender
 Message encrypted using Alice’s private key (DA), must
be Alice
 Message cannot be repudiated
 Message encrypted using Alice’s private key (DA), must
be Alice
 Message cannot be altered nor concocted
 Message encrypted using Alice’s private key (DA),
Bob/Trudy cannot fake this

EEEN30024 - Data Networking - Lecture 18 16


Message Digests
 Compute a one-way hash function that
guarantees the contents of the message
 Message cannot be altered
 Bob/Trudy cannot produce a message that produces
the same digest

17
EEEN30024 - Data Networking - Lecture 18

Message Digest
Properties
 H can be applied to a block of data of any size
 H produces a fixed-length digest
 Given P, H(P) is easy to compute
 Given H(P) it is impossible to find P
 Not necessary for all implementations

 Given P, P’ cannot be feasibly be found such that


H(P’) = H(P)
 known as a hash collision
 A change of 1 bit in P, causes a very different
H(P) to be produced

EEEN30024 - Data Networking - Lecture 18 18


Example Message Digest – SHA-1

 SHA = Secure Hash Algorithm


 Input
 a plaintext message <264 bits long
 Output
 a 160-bit message digest, where every bit of the
message digest is a function of every bit of the input
 Processing is similar to symmetric-key
cryptography algorithms
 a number of positional changes and basic logical
functions are used.

EEEN30024 - Data Networking - Lecture 18 19

SHA-1 and SHA-2


 SHA-1 is vulnerable to attack
 Collisions may be identified in a 263 attack
 better than the 280 that a birthday attack would
suggest

 Versions with longer digests have been developed


 Collectively these are known as SHA-2
 SHA-224, SHA-256, SHA-384 and SHA-512

EEEN30024 - Data Networking - Lecture 18 20


Using Message Digests

 Whilst message digests protect against


modification of a message, they do not deal with
 Verification of the sender
 Repudiation of a message
 Message concoction

 Thus, there needs to be some way associating


authorship with the message

EEEN30024 - Data Networking - Lecture 18 21

Message digests
and authorship

De-
En-

EEEN30024 - Data Networking - Lecture 18 22


Message Digests
and the Birthday Attack
 The birthday attack can be used on a message
digest
 The idea is to produce a collision, i.e. two
messages such that H(X)=H(Y)
 that might be used for advantage

 It is called the ‘birthday attack’ after the


mathematical problem that asks how many
people are needed before there is a probability of
> 0.5 of them sharing the same birthday

EEEN30024 - Data Networking - Lecture 18 23

Message Digests
and the Birthday Attack
 n possible inputs with m possible outputs
 There are possible input pairs

 If the chance of at least one matching pair is


good, i.e.

 A match is likely for

 Thus a 64-bit digest can yield a collision in


around 232 attempts

EEEN30024 - Data Networking - Lecture 18 24


Message Digests
and the Birthday Attack
 To generate a pair of messages with the same
message digest but different meanings include 32
alternates in each of the messages.

 The idea is to have alternate phrases in the two


documents
 … He is [clearly | obviously] the [outstanding | cleverest]
student in the [class | cohort] …
 … He is [clearly | obviously] the [dumbest | stupidest]
student in the [world| universe] …
 Generate all possible 232 digests for both
documents and hope to find a match.
 If no, alter documents again and retry.

EEEN30024 - Data Networking - Lecture 18 25

Message Digests
and the Birthday Attack

 The longer the digest, the less feasible it is to


conduct a a birthday attack

 Suppose it is possible to produce 1x109 digests


per second
 232 digests require 4.3 seconds

 264 digests require 585 years

 280 digests require 3.8x1016 years

EEEN30024 - Data Networking - Lecture 18 26


Lecture 19:
Network Security 3
Key Distribution
Authentication Mechanisms

EEEN30024 - Data Networking - Lecture 19 1

Learning Outcomes
 Be able to
 Explain Public Key Infrastructure (PKI).
 Explain various Authentication Protocols and
state how they are vulnerable to attack.
 Explain how key exchange protocols function and
be able to calculate the key from n, g, x and y
using the Diffie-Hellman key exchange.

EEEN30024 - Data Networking - Lecture 19 2


Key Distribution
 Asymmetric key cryptography requires the
distribution of demonstrably authentic public
keys.
 If public keys cannot be traced back to their
owners, attacks may be mounted.
 Consider the example on the next slide
where Trudy inserts herself between Alice
and Bob.

EEEN30024 - Data Networking - Lecture 19 3

Key Distribution – No Certification [1]

 Trudy is reading messages from Alice to Bob


without either Alice’s or Bob’s knowledge
 Alice needs some way to determine that the public
key she receives is authentic
 Need to use a certificate
EEEN30024 - Data Networking - Lecture 19 4
Public Key Certificates
 Public key is provided with a certificate of
authenticity
 Bob’s key and his identity
 This is done by a centralised certification
authority (CA)
 The CA ‘signs’ the certificate using the CA’s
private key
 The certificate can then be validated by Alice
using a well-known public key for the CA

EEEN30024 - Data Networking - Lecture 19 5

Public Key Certificates


 Implies that there is a single, global CA who is
trusted by all
 This gives rise to a number of issues
 If there is a single CA, won’t it quickly become overloaded
by demand?
 Spread the work
 If the work is spread, how is knowledge of the CA’s private
key restricted?
 Use a hierarchical system of delegated authority, each
delegated CA has its own key
 If delegated authority is used, how does a Alice know to
trust the delegated CA?
 Use a hierarchical system of certificates
 Can a single authority be trusted?
 No use several

EEEN30024 - Data Networking - Lecture 19 6


Centralised CA
 A single CA would become overloaded with work
 Could have parallel systems to share work, but there is a
danger that the CA’s private key may become
compromised
 Thus, develop a hierarchical system where a Root CA
delegates its authority through Regional CAs to Local
CAs

EEEN30024 - Data Networking - Lecture 19 7

Public Key Infrastructure (PKI)


 The hierarchy of delegated authority through
CAs is called Public Key Infrastructure (PKI)
 So Bob gets his certificate signed by his local
CA, how does Alice know that this is valid?
 The local CA will have a certificate from the
CA above it
 Again, Alice needs to be assured that this is valid
 Thus the path must be traced back to the root
CA
 Alice knows this is valid since the public key of the
root CA is known
EEEN30024 - Data Networking - Lecture 19 8
PKI and certificates
 The previous slide implies that Alice must check
Bob’s certificate with the local CA and then check
the regional CA, until she reaches a CA one below
the root CA
 In practice, Alice does not need to contact these
CAs. Bob will include the set of certificates from all
CAs up to the root in his certificate
 Because Alice knows the public key of the root, she
can validate the chain of certificates from the root to
Bob’s without contacting any CA
 Known as a chain of trust or certification path

EEEN30024 - Data Networking - Lecture 19 9

Multiple Certification Authorities


 There is no one organisation that is considered
trustworthy enough to act as a single, centralised
certification authority
 In practice, several authorities are used
 The public keys of these authorities need to be
known and most web browsers are supplied with a
number (around 100) programmed in
 These are known as trust anchors
 Alice can determine Bob’s identity if the certification path
supplied can be traced back to a trust anchor
 PKIs use a protocol called X.509 and thus generate
X.509 certificates

EEEN30024 - Data Networking - Lecture 19 10


Authentication
 The authentication of a remote
system in the face of an active
intruder
 Trudy may intercept, replay, and modify messages to trick
either or both of Bob and Alice or simply to interfere with the
communication
 Authentication is a surprisingly difficult problem and a number
of protocols exist
 In general, most protocols develop a one-time session key
(symmetric key – e.g. AES) that is used for the communication
 Asymmetric key cryptography is often used to establish the
session key

EEEN30024 - Data Networking - Lecture 19 11

Two-way Authentication [2]


Shared Secret Key
A = Alice’s Identity 1. A
B = Bob’s Identity 2. RB
K = Shared Key
R = Random Alice 3. K(RB) Bob
Number or nonce 4. RA
5. K(RA)

 Alice sends her identity (plaintext), Bob challenges with a nonce


 Alice responds with Bob’s nonce encrypted using the shared secret
key and issues her own challenge using a nonce
 Bob responds encoding the Alice’s nonce using the shared secret
key
 The session can now be established
 If required, a one-time session key can be used by Alice picking a key
and sending to Bob encrypted using the shared key

EEEN30024 - Data Networking - Lecture 19 12


Two-way Authentication [2]
Shared Secret Key – Reduction in Messages
A = Alice’s Identity
B = Bob’s Identity 1. A, RA
K = Shared Key 2. RB, K(RA)
R = Random Alice Bob
Number or nonce 3. K(RB)

 Reduces number of messages from 5 to 3


 Alice sends her identity and her nonce in first message
 Bob responds to the challenge by encoding the nonce using
the shared key and providing his challenge by way of a nonce
 Alice responds to the challenge by encoding Bob’s nonce
using the shared key
 Connection established
EEEN30024 - Data Networking - Lecture 19 13

Two-way Authentication
Shared Secret Key
 Requires that key be established a priori.
 The 3-step protocol can be defeated by a
reflection attack by Trudy (next slide)
 This is easier if Bob can have multiple concurrent
sessions.
 The 5-stage protocol also has vulnerabilities
 If Alice is a general purpose computer with which
Trudy can open sessions, Trudy can mount a
reflection attack
 not considered in this lecture

EEEN30024 - Data Networking - Lecture 19 14


Two-way Authentication [2]
Shared Secret Key – Reflection Attack
1. A, RT
A = Alice’s Identity 2. RB, K(RT) Session 1
B = Bob’s Identity
T = Trudy’s Identity 3. A, RB
K = Shared Key Trudy Bob Session 2
4. RB2, K(RB)
R = Random
Number or nonce 5. K(RB)
Session 1

 Trudy claims to be Alice and sends her own nonce


 Bob responds to the challenge and provides his own nonce
 Trudy then starts another session, again using Alice’s identity but
sending Bob’s nonce back to him as her challenge
 Bob responds by producing a second nonce, but, more crucially by
encoding his original nonce using the shared secret key
 Trudy now has the response to the challenge for the first session
and the first session is now established with Trudy pretending to be
Alice
EEEN30024 - Data Networking - Lecture 19 15

Two-way Authentication
Shared Secret Key – Reflection Attack
 General rules for addressing the issue:
 Make the initiator prove his/her identity before the
responder does
 Bob gives his identity before Trudy has supplied any
useful information.
 Use a pair of shared keys – one for initiator and
one for responder.
 Use nonces from different sets
 e.g. Even for initiator, odd for responder
 Ensure that information from one concurrent
session cannot be usefully used in another.

EEEN30024 - Data Networking - Lecture 19 16


Two-way Authentication
Shared Secret Key – Preventing Attacks
 Protocols can be developed to overcome the
replay attack
 These get quite complex
 An alternative approach is shown on the next
slide
 In this case a HMAC (Hashed Message
Authentication Code) is computed
 This is a one-way has function
 See Lecture 19 for details of a one-way hash function
 The protocol includes the secret shared key that
cannot be known by Trudy
EEEN30024 - Data Networking - Lecture 19 17

Using HMAC
A = Alice’s Identity
B = Bob’s Identity 1. A, RA
K = Shared Key 2. RB, HMAC(RA, RB, A, B, K)
R = Random Alice Bob
Number or nonce 3. HMAC(RA, RB, K)

 Alice sends a nonce


 Bob sends his own nonce together with the hash function of Alice’s nonce,
his own nonce, the identities of Alice and Bob and the shared key
 Alice responds with a hash function of the nonces and the shared key
 Trudy cannot interfere as her previous method of getting a principal to
encode a number of her choice does not work as both hash functions have
values of the principals’ choosing

EEEN30024 - Data Networking - Lecture 19 18


Establishing a Shared Key
 So far we have assumed that Alice and Bob share a
key

 Is there a way in which they can establish a shared,


private key in full view of other users?
 yes, using the Diffie-Hellman key exchange

 Alice and Bob agree on two large numbers, n and g


 n as prime where is also a prime

 n and g are exchanged in full view of Trudy

EEEN30024 - Data Networking - Lecture 19 19

Diffie-Hellman Key Exchange [2]


Alice picks a large secret
number = x
1. n, g, gx mod n
Bob pick a large secret
number = y Alice 2. gy mod n
Bob

 Key is gxy mod n


 Alice can compute this since she knows x and gy mod n
 (gy mod n)x = gxy mod n
 Bob can also compute thus since he knows y and gx mod n
 (gx mod n)y = gxy mod n
 Trudy cannot compute this since she sees only gx mod n and gy
mod n and cannot compute x and y from these
EEEN30024 - Data Networking - Lecture 19 20
Diffie-Hellman Key Exchange
Example

 n = 23, g = 5
 Alice x = 6
 Bob y = 15
 Alice sends 23, 5, 56 mod 23 (=8)
 Bob sends 515 mod 23 (=19)
 Key is 5(6x15) mod 23 = 2
 Alice by 196 mod 23 = 2
 Bob by 815 mod 23 = 2

EEEN30024 - Data Networking - Lecture 19 21

Diffie-Hellman Key Exchange


Vulnerability to man-in-the middle attack
Picks x Picks z Picks y
1. n, g, gx mod n
2. n, g, gz mod n

Alice 3. gz mod n Trudy Bob


4. gy mod n

 Trudy can establish secret keys with both Bob and Alice
provided she can intercept all messages
 Thus the key exchange is vulnerable
 Moreover, it is not efficient in the long term as a private key is
needed for each communication partner

EEEN30024 - Data Networking - Lecture 19 22


Authentication with a Key Distribution
Centre
1. A, KA(B, Ks)
2. KB(A,KS)
Alice KDC Bob

 Trusted Key Distribution Centre (KDC) shares a private key


with each party
 Alice KA, Bob KB
 Alice contacts the KDC indicating her identify and sending
Bob’s identity and a session key to the KDC
 The KDC verifies Alice (by the use of KA) and passes the
identity of Alice and the session key to Bob encrypted using
the private key it shares with Bob

EEEN30024 - Data Networking - Lecture 19 23

Authentication with a Key Distribution


Centre
 This is susceptible to a ‘replay’ attack where Trudy
can replay the message from the KDC to Bob and
any message that followed it.
 Therefore, Trudy is limited to replaying actions of
Alice, but this may be of benefit to Trudy and almost
certainly to the detriment of Alice.
 Time stamping messages can severely restrict the
window of opportunity for such an attack.
 Placing a nonce in each message also protects,
provided that nonces are not repeated in the time
period.
 More sophisticated protocols have been developed
 The next slide shows the Needham-Schroeder Protocol:

EEEN30024 - Data Networking - Lecture 19 24


Needham-Schroeder Protocol
1. RA, A, B
2. KA(RA, B, KS, KB(A, KS)) KDC

Alice 3. KB(A, Ks), KS(RA2)


Bob
4. Ks(RA2-1), RB
5. KS(RB-1)

1. Alice informs the KDC she wishes to establish a session with Bob.
2. KDC replies with a message encrypted using Alice’s key containing
Alice’s challenge, Bob’s identity, a session key and a coded using
Bob’s key with Alice’s identity and the session key.
3. Alice passes the message from the KDC to Bob and encodes a
challenge using the session key.
4. Bob responds to the challenge with a value one less than the
nonce RA2 and, to prevent a replay by an intruder from Step 3, Bob
issues his own challenge.
5. Alice responds to the challenge with a value one less than RB,
again to nullify interception of Step 4.
EEEN30024 - Data Networking - Lecture 19 25

Authentication Using Kerberos


 Kerberos is a widely used variant of the
Needham-Schroeder protocol.
 With Alice as a client and Bob as a server
there is a three-stage process:
 Alice must log in to an authentication server to
be verified as being Alice.
 Alice must then access a ticket-granting server
to gain a ticket that proves her identity.
 Alice can then access Bob with information she
has gained from the ticket-granting server.
EEEN30024 - Data Networking - Lecture 19 26
Using Kerberos
1. A Authenti-
2. KA(KS,KTGS(A,KS)) cation
Server (AS)
3. KTGS(A,KS), B, Ks(t) Ticket-
Alice 4. KS(B, KAB), KB(A, KAB) Granting
Server (TGS)
5. KB(A, KAB), KAB(t)
6. KAB(t+1) Bob

 t = time

EEEN30024 - Data Networking - Lecture 19 27

Using Kerberos
 Alice types her name at a workstation it is sent to AS.
 AS responds with a session key (KS) and an
encrypted message for the TGS containing Alice’s
identity and the session key.
 The workstation now asks for Alice’s password, the
password generates KA so the AS’s message can be
decrypted, Alice’s password can now be deleted by
the workstation.
 Alice then sends a message to the TGS consisting of
the encrypted message she received from the AS
together with Bob’s identity and the timestamp (t)
encrypted using the session key.

EEEN30024 - Data Networking - Lecture 19 28


Using Kerberos
 Alice receives a Bob’s identity and a session
key to use with Bob (KAB) together with a
message to send to Bob that uses Bob’s
secret key and includes Alice’s identity and
the session key for Bob and Alice to use.
 Alice then sends the encrypted message she
gets from the TGS to Bob together with a
timestamp (encrypted using the session key).
 Bob confirms the session has started by
returning an updated timestamp encrypted
using the session key.
EEEN30024 - Data Networking - Lecture 19 29

Using Kerberos
 If Alice wishes to start a session with another server,
she simply sends a message to the TGS in the form
of Step 3, but with the identity of the new server
instead of Bob.
 ASs and TGSs are distributed into multiple realms
 To communicate with a server in another realm Alice
asks her TGS for a ticket that will be recognised by
a TGS in the other realm.
 TGSs therefore need to register with TGSs in
remote realms
 in the same way as servers must be registered with their
local TGS.

EEEN30024 - Data Networking - Lecture 19 30


Authentication Using Public-Key
Cryptography
1. supply EB 4. supply EA
PKI
2. here’s EB 5. here’s EA
3. EB(A, RA)
Alice Bob
6. EA(RA,RB,Ks)
7. KS(RB)

 Alice gets Bob’s public key.


 She uses this to send her identity and a nonce.
 Bob doesn’t know who Alice is, so he gets her public key and
then sends back her nonce, a new nonce and a session key.
 Alice completes the establishment of the session by
responding to Bob’s challenge encrypted using the session
key.

EEEN30024 - Data Networking - Lecture 19 31

You might also like