TCP/IP Solutions: Teacher's Guide
TCP/IP Solutions: Teacher's Guide
TCP/IP
Solution
Teachers’ notes
V1.0.1
Contents
1 Getting started.................................................................................................................................6
1.1 Required hardware ................................................................................................................6
1.2 Test routine............................................................................................................................6
1.3 Required software..................................................................................................................6
1.4 Additional software ...............................................................................................................7
1.5 Documentation ......................................................................................................................7
1.6 Examples and exercises.........................................................................................................7
1.7 Disclaimer .............................................................................................................................7
2 Introduction.....................................................................................................................................8
2.1 Using this course ...................................................................................................................8
2.2 Who this course is aimed at...................................................................................................8
3 TCP/IP basic concepts ....................................................................................................................9
3.1 What is TCP/IP?....................................................................................................................9
3.2 OSI layers..............................................................................................................................9
3.3 TCP_IP component modes ..................................................................................................10
3.4 Frames and datagram’s - Messages within messages..........................................................10
3.4.1 The Ethernet physical layer ............................................................................................11
3.4.2 Onto the network with IP................................................................................................11
3.4.3 Delivering data with TCP ...............................................................................................12
3.4.4 Applications and content ................................................................................................12
3.5 Other Protocols....................................................................................................................12
3.5.1 ARP – Address Resolution Protocol...............................................................................12
3.5.2 ICMP – Internet Control Message Protocol....................................................................12
3.5.3 UDP – User Datagram Protocol......................................................................................12
4 Hardware and software .................................................................................................................13
4.1 Practical limitations for the PICmicro .................................................................................13
4.2 The internet board ...............................................................................................................13
4.3 Flowcode and the TCP_IP component ................................................................................14
4.4 Basic direct connection setup ..............................................................................................14
4.5 Dual Ethernet board system.................................................................................................15
4.6 Network monitoring software..............................................................................................15
4.6.1 Debugging with Network traffic analysis tools ..............................................................16
4.7 Packet injectors....................................................................................................................16
4.7.1 Debugging with Packet injectors ....................................................................................17
4.8 Server configuration ............................................................................................................17
5 The TCP_IP component................................................................................................................19
5.1 TCP_IP properties ...............................................................................................................19
5.2 TCP_IP component macros.................................................................................................19
6 Ethernet layer................................................................................................................................20
6.1 Overview .............................................................................................................................20
7 Address Resolution Protocol.........................................................................................................22
7.1 What’s it used for? ..............................................................................................................22
7.1.1 ARP in action: finding the MAC address for a message ................................................22
7.2 Ethernet frame: The outer wrapper......................................................................................23
7.3 The ARP datagram ..............................................................................................................23
8 Implementing Ethernet mode in Flowcode ...................................................................................25
8.1.1 Initializing.......................................................................................................................25
8.1.2 Creating a MAC socket ..................................................................................................25
8.1.3 Sending data ...................................................................................................................25
8.1.4 Reading in the data .........................................................................................................26
8.1.5 Matching data .................................................................................................................26
9 Exercise 1: ARP scanner...............................................................................................................27
10 Worked Example: Implementing ARP in Flowcode.....................................................................28
10.1 Network traffic analysis ......................................................................................................28
10.2 The basic structure...............................................................................................................28
10.3 Initializing ...........................................................................................................................29
10.4 Sending the ARP request.....................................................................................................30
10.4.1 ARP datagram............................................................................................................30
Page 2 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 3 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 4 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 5 of 79
EB921 TCP/IP Solution Teachers’ notes
1 Getting started
The following information is designed to aid you in getting the E-blocks internet solution up and
running.
Port E
+V GND
0
1
J6 J1 PB1 2 LDR
J99 3 RV1
12
4 ANA SEN
5 D IN
P ort A 6 D OUT
1
e
U1
blocks
Sensors
0V +5V
LED1
J10
J11
B5
B4
B3
X1
Z1 Port B
e e
PIC16F877
SW2
blocks
J5 LEDs 5V 0V
U8/14 blocks
lcd
8 pin
SW1
D7 D6 D5 D4 D3 D2 D1 D0
e
40
www.m atrixmultimedia .[Link]
blocks ONLY INS ERT 1 CHIP AT A TIME
EB006001
USB multiprogrammer
Port D
Port C
0
5V 5V 0V
1
2
e
e
switches
SDA
3
SCL
blocks
4
/INT blocks
5 EB-023-00-1
6 Internet board
7
www .m atrixm ulti [Link]
5V
5V
0V
Install and setup instructions for the E-blocks internet solution can be found on the datasheets supplied
on the ELSAM CD as part of the E-block internet solution
Additional test routines are available for the other e-blocks on the ELSAM CD – see the relevant e-
blocks sub folders for details.
Page 6 of 79
EB921 TCP/IP Solution Teachers’ notes
1.5 Documentation
Documentation for the various E-blocks and other items supplied as part of the internet solution is
provided on the ELSAM CD supplied as part of the E-block internet solution.
Information supplied on ELSAM is correct at the time of pressing; however for the latest E-blocks
documentation visit the E-blocks members’ area of the Matrix Multimedia web site:
[Link]
The section is password protected and needs the following Login details.
Username: eblocks
Password: halifax
Note that the server is case sensitive so enter the login details exactly as listed above.
1.7 Disclaimer
The information contained here is correct at time of going to press (August 2005), but may be
superseded or changed at a later date. If this information is superseded a revised Getting started
document will be issued with the E-blocks internet solution.
Page 7 of 79
EB921 TCP/IP Solution Teachers’ notes
2 Introduction
The TCP/IP Course is designed to introduce you to the concepts required to understand the
communication protocols generally referred to as TCP/IP, including the Ethernet, TCP, IP, UDP and
other protocols.
This course is carried out using Flowcode, which is shipped with the TCP/IP solution.
Flowcode uses the TCP/IP component which has a number of properties and macros to allow the
student to build up the system they require. This allows students to learn about TCP/IP without getting
bogged down in the problems of programming in C or a lower level language.
A number of exercises are included along with notes on how implement the exercise in Flowcode. For
the first few protocols the notes are relatively extensive, forming a kind of walkthrough of the exercise.
For later exercises the notes become more geared towards explaining specifics and how the protocol
differs from those previously covered. By that stage the student should have sufficient understanding of
the basics involved to complete the task without extensive notes. Example solutions are provided for
the exercises for demonstration, discussion and use as a starting point for further programming.
• Electronics technicians will generally have some experience with Microcontrollers, and will
be mostly concerned with implementing TCP/IP communications from a practical point of
view – i.e. how to create programs and send data.
The general goal of the Electronics technician will be to send messages.
• Network technicians and Computer will be more concerned with gaining an understanding of
the communications process itself i.e. datagram’s and frameworks, and how this relates to the
data viewable with network analyzer tools.
The general goal of the Network technician will be to understand and debug messages on the
network, and to troubleshoot communications errors.
Both groups are catered for in equal measure, with both the theory and the practical aspects being
covered. It will be up to the teacher involved to place the emphasis during teaching.
Page 8 of 79
EB921 TCP/IP Solution Teachers’ notes
We can refer to TCP/IP in both a general and a specific way. The general term TCP/IP is used here to
refer to the messaging system that transfers data between computers via the internet. The end result can
be Email, web pages, or a data file. The process of transferring the message will involve a number of
layered communication protocols. One of these can be TCP. One of them could be IP. And there are
others – Ethernet, ICMP, UDP etc. This is where the specific definition of TCP/IP comes in, or rather
the specific definition of TCP and the specific definition of IP. TCP and IP are two of the more
important protocols used in internet communications, hence the general term TCP/IP to describe the
whole process.
Note: Here we will use TCP/IP to refer to the general system, and TCP and IP to refer to the specific
protocols.
In the higher level layers more and more of the data transmission process becomes automated. For
example users do not need to know how the routers will find the correct recipient for an IP data
transmission – they only need to know that the routers can. Provide the correct IP address and the data
will get there whether it’s across the room, or across the world.
In the higher level layers more and more consideration is given to error detection and transmission
sequencing, and it is likely that the receiving system will expect a two-way dialogue with data being
passed in a specific sequence, and with error codes being returned at specific times. Checking for these
codes and dealing with any errors means a corresponding increase in data processing.
Page 9 of 79
EB921 TCP/IP Solution Teachers’ notes
The Application layer protocols are the parts that we normally associate TCP/IP with – web browsers
and email programs etc. Many would think of them as TCP/IP, but in truth they just manipulate and
display the raw data sent by TCP/IP. What you see in an email program is not SMTP (Simple Mail
Transfer Protocol), but a visual representation of the data sent via TCP/IP in the SMTP format.
The modes automate the levels below them, so implementing the TCP mode for instance will handle
the Network (IP) and Physical (MAC) layers automatically. Headers are also handled automatically in
all but MAC mode allowing you to concentrate more on the data processes.
Page 10 of 79
EB921 TCP/IP Solution Teachers’ notes
The graphic shown above displays the format for a number of different protocols. The graphic also
nicely shows how datagram’s can be layered inside other datagram’s.
A real life packet would have details such as address to be delivered to, return address, postage type
(Airmail, 1st class etc.), customs clearances, post stamps etc. An IP datagram has the same kind of
information contained in its header section: Source IP address, Destination IP address, Protocol etc.
IP differs from Ethernet in that it is not limited to a direct connection. Ethernet can only pass the
message on to another MAC device; generally this will be one in the same Local Area Network. IP
however goes out into the wilds. The IP address is examined and the datagram passed on either locally
or globally depending on where the IP address is. The receiving devices know how to decipher the IP
Page 11 of 79
EB921 TCP/IP Solution Teachers’ notes
address and how to determine where to send it to next. There will be a whole host of systems swinging
into action to aid the packet on its journey, but we won’t see them, just like we don’t see the baggage
handlers and drivers that shuffle the mail around the country. These background details don’t concern
us, only the fact that the message will get through – unless there is some kind of problem.
Servers can be down. Addresses can be wrong. The message may not always get through on such
occasions. The senders address is part of the data sent so should the destination be blocked or missing
an error message can be returned to the sender to inform them of what the problem is.
An important point to note here is that the contents of the message are irrelevant; it’s the
communication that counts: what the email or web page actually says doesn’t matter to TCP – the
important issue is getting the data to the application, and letting the application worry about content,
fonts, formatting and all the other things that need doing to the data. It’s the job of TCP to get the data
there, that’s all.
Page 12 of 79
EB921 TCP/IP Solution Teachers’ notes
Port E
+V GND
0
1
J6 J1 PB1 2 LDR
J99 3 RV1
12
4 ANA SEN
5 D IN
P ort A 6 D OUT
1
7
U1
blocks
Sensors
0V +5V
LED1
J10
J11
B5
B4
B3
X1
Z1 Port B
e e
PIC16F877
SW2
blocks
J5 LEDs 5V 0V
U8/14 blocks
lcd
8 pin
SW1
D7 D6 D5 D4 D3 D2 D1 D0
e
40
www.m atrixmultimedia .[Link]
blocks ONLY INS ERT 1 CHIP AT A TIME
EB006001
USB multiprogrammer
Port D
Port C
0
5V 5V 0V
1
2
e
e
switches
SDA
3
SCL
blocks
4
/INT blocks
5 EB-023-00-1
6 Internet board
7
www .m atrixm ulti [Link]
5V
5V
0V
A sensor board is connected to Port A, LED’s and an LCD display on Port B, and switches on Port D.
The internet board needs to be connected to Port C due to the design of the PIC16F877A chip used.
This layout will be used with the examples and exercises in this course.
Also it may not be possible to perform multiple functions and use multiple protocols and levels of
communications in the same program due to memory limitations. The PICmicro has limited memory
and needs some spare capacity for the program to actually function. The size and complexity of the
code generated to support the TCP_IP component macros can take up a large part of the ROM and
RAM space, leaving you with a much reduced amount of memory in which to develop your program.
Unfortunately you may only learn that your program is just too big to fit into the memory when the
assembler tells you that you have run out of space.
We have chosen to use a PIC16F877A device with the internet board connected to Port C. Port C is
used as the internal communication between the boards uses Master I2C™ (MI2C™), which is on Port
C. If you use another PICmicro device you will need to ensure that it has MI2C™ capabilities, and to
determine which port they are on. Note that MI2C™ is not the same as I2C™ found on many other
devices. Please check the device datasheet before using other devices.
Page 13 of 79
EB921 TCP/IP Solution Teachers’ notes
A reasonable level of competence in creating Flowcode programs is assumed. It will be assumed in this
document that the user is familiar with adding and editing macros and dealing with component
properties. If the user requires further training with Flowcode we recommend that they review the
tutorial files, and work through Flowcourse (available on the Flowcode CD ROM).
You may need to configure the PC to have a set IP address, and to not use proxy servers.
This is detailed in the internet board datasheet but will be briefly summarized here.
The IP address can be set up in the Network Connections Dialog screen. A [Link] address such
as [Link] is generally recommended for use with the internet board. Please note down the
original IP address details before making any changes. If in doubt ask a network technician for aid.
Note that example files will require the programs target IP address setting to one that you have selected
here.
Page 14 of 79
EB921 TCP/IP Solution Teachers’ notes
The LAN proxy server setting can be found in the Internet Options Control Panel.
Ensure that Use a proxy server is not ticked.
When using a splitter cable you will need to configure the second board to use the patch system so that
you can give it a separate Interrupt connection to the other board. Details of this can be found in the
EB023 Datasheet.
Page 15 of 79
EB921 TCP/IP Solution Teachers’ notes
We have included a copy of Ethereal on the CD, and will be discussing using Ethereal to help debug
programs later in the document.
Note: Ethereal requires certain extra files in order to run (WinPcap). These files are auto-installed by
the packet Excalibur program should you be installing both. The latest WinPcap installer is included on
the CD. Alternatively you can download the latest version from [Link]
The following image is taken from Ethereal. Note that the various sections allow you to select
messages to examine and to see the various protocols contained in the message.
Data is shown about the various elements in the protocol e.g. “Type: IP (0x0800)” or the “Src Addr” IP
address details. The various levels and sub categories for the data involved can be expanded as well.
The original raw data is also available at the bottom in both Hex and ASCII format.
Page 16 of 79
EB921 TCP/IP Solution Teachers’ notes
We have included a copy of Packet Excalibur on the CD, and will be discussing using Excalibur to help
debug programs later in the document.
The following image is taken from Packet Excalibur and shows an ARP request being built.
Note how the various parts of the packet are built up on each other. Drop down menus and edit boxes
are used to add the various elements forming the final packet that can be seen at the bottom in
Hexadecimal and ASCII format.
Packet injectors require a good working knowledge of TCP/IP as all stages of the packet require
building. However a network traffic analyzer such as Ethereal can be used in conjunction with the
Packet injector to find much of the required information for packet building.
Page 17 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 18 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 19 of 79
EB921 TCP/IP Solution Teachers’ notes
6 Ethernet layer
6.1 Overview
The Ethernet layer is the physical layer of the OSI model. It handles communications between the
originating device and the other physical devices in the network such as hubs or switches. All
communications on an Ethernet based network are done as Ethernet frames. Higher level protocols
transmit their message inside the data section of an Ethernet frame. This message in a message is
stripped out and processed by the receiving node. But the fundamental basic level of communication is
at the physical level from MAC device to MAC device.
The Ethernet frame consists of a header section, a data section and a checksum section.
The Ethernet layer is also known as the MAC layer after the Media Access Controller devices that
handle the communications. When working with the Ethernet layer the terms MAC mode and Ethernet
mode can be used interchangeably. Each MAC device has a built in unique 6 byte identifier known as a
MAC address. This ensures that no two devices on the network have the same MAC address. By
passing the source and destination MAC addresses along with the data the message can be error
checked and responded to. The first three bytes are generally used as a company identifier, and the final
three bytes are used to give each device from the company a unique ID.
Normally the MAC identifier is hard coded into a device at manufacture and can not be changed.
However the E-Blocks internet boards have a user definable MAC identifier. This is so that you can set
up specific MAC identifiers for testing and debugging. The default MAC address for the internet board
is: [Link].0.0, with 0.8.220 being the company ID for the makers of the particular device used on the
internet board.
When using more than one internet board you need to ensure each board has a unique MAC address.
Otherwise the Ethernet layer protocols will be unable to differentiate between boards, which will lead
to problems.
Ethernet Frame
Page 20 of 79
EB921 TCP/IP Solution Teachers’ notes
Explanation Bytes
Destination The Destination MAC address can be the 6 byte MAC address of a 6
known node, or a general address such as the broadcast address 255,
255, 255, 255, 255, 255.
Source The Source MAC address is the MAC address of the sending node. 6
Type The type section can vary depending on what protocol you are using. 2
For example the ARP protocol has the type data: 8, 6.
Data The data section can be from 46 to 1500 bytes in length. If the data 46 to
section is less than 46 bytes it will need to be padded with extra bytes 1500
to bring it up to 46 bytes.
Checksum The Ethernet frame is rounded off by a 4 byte checksum number. 4
Fortunately this is generated by the TCP_IP component so you will
not normally need to deal with it.
Page 21 of 79
EB921 TCP/IP Solution Teachers’ notes
ARP is as close as we can get to working with the Physical layer itself. ARP is a message that fits
inside the Ethernet frame data section and can be acted upon directly. Unlike higher level protocols that
may consist of messages within messages which required extracting and processing before being acted
upon. The higher levels, such as IP and TCP use the Ethernet Physical layer as the outer physical
wrapper in which their own datagram is sent. However the TCP_IP component handles this wrapping
behind the scenes so we never actually see it in action when using those modes.
Example:
1. Node A needs to send a message to IP address [Link] but does not know the MAC
address to send to.
2. Node A broadcasts an ARP request for IP address [Link] to all nodes on the network
Page 22 of 79
EB921 TCP/IP Solution Teachers’ notes
3. Node B (IP address [Link]) receives the message but ignores it.
4. Node C (IP address [Link]) receives the message and responds, sending its MAC address
with the reply.
5. Node D (IP address [Link]) receives the message but ignores it.
6. Node E (IP address [Link]) receives the message but ignores it.
7. And so on for all the other nodes in the network which will ignore the message.
8. Node A receives the reply from Node C and extracts the MAC address for IP address
[Link].
9. Node A is now ready to send the message.
In addition to being able to send the message the Node can also save the IP address/MAC address
combination for future reference so that it does not need to clog up the network with broadcasts trying
to find the same IP address later on. On a network with say 200 nodes this could represent a significant
reduction in network traffic.
Ethernet header
Explanation Bytes Notes
Destination The destination MAC address. 6 Using the MAC
broadcast address
[Link].255.255
will pass the message to
all MAC devices on the
Local Area Network.
Source The MAC address of the sending device. 6 Available in the TCP_IP
component property
page.
Type The operation type 2
Data
The Ethernet data section needs to be 46 or more bytes long. If the data length is less it needs to be
padded out. Fortunately the TCP_IP component will handle this automatically.
Checksum
A checksum is needed at the end, but this too is handled automatically by the TCP_IP component.
Page 23 of 79
EB921 TCP/IP Solution Teachers’ notes
ARP datagram
Explanation Bytes Notes
Hardware type: The type of hardware used. 2
generally this will be an Ethernet
connection, value 0x0001
Protocol type The type of protocol used. 2
IP = 0x0008.
H/W adjustment The Hardware length is the length of 1
length the hardware identifier, in this case 6
for the 6 byte MAC address.
Protocol adjustment The Protocol length is the length of the 1
length protocol identifier, in this case 4 for the
4 byte IP address.
Operation The operations value that we will be 2
using are 0,1 for an ARP request, and
0,2 for an ARP reply.
Sender hardware The MAC address of the sending 6 The default is [Link].0.0
address hardware device.
Sender IP The IP address of the sender. 4 The default is [Link]
Available on the component properties
page.
Target hardware Needs to be filled in, but is ignored by 6
address the receiving device.
Target IP address: The IP address that we wish to check 4
for.
One important point not to overlook is that the ARP datagram is wrapped up in the data section of the
Ethernet frame – a message in a message. When the Ethernet device at the other end receives the
Ethernet message the ARP datagram will be split out and processed by the node. The job of the
Ethernet frame is simply to ensure that the message arrives.
Page 24 of 79
EB921 TCP/IP Solution Teachers’ notes
Note: This section covers the fundamentals of sending and receiving data, and should be read
before moving on to the other protocols.
8.1.1 Initializing
Before anything can be done the TCP_IP component requires initializing.
This initializing is required by all programs using the TCP_IP program.
Add an ‘Initialize’ macro to the beginning of your program to initialize the TCP_IP component.
As Create_MAC_Socket returns a non-zero value if the connection is successful you can use this return
value for error checking to inform the user that there has been a problem and end the program.
Once you have the data ready the process of sending a message is as follows:
• Tx_start (channel)
Readies the buffer to begin accepting transmission data.
• Tx_sendbyte(channel, byte)
Sends the data byte to the buffer for the specified channel.
Needs repeating until all the data has been sent to the buffer.
Two other useful macros that send Property data are available as well:
Tx_sendmymac
Sends the TCP_IP components MAC address (6 bytes)
Tx_sendmyip
Sends the TCP_IP components IP address (4 bytes)
• Tx_end (channel)
Used to initiate the data transmission.
The data sent to the buffer is then transmitted.
Page 25 of 79
EB921 TCP/IP Solution Teachers’ notes
Other items that are required, such as data padding and the checksum, are handled automatically by the
TCP_IP component.
Once you have collected all the data you need from the message you will need to clear the data buffer
to allow the next message to come in.
Page 26 of 79
EB921 TCP/IP Solution Teachers’ notes
Exercise objective:
• To build a program that can scan a range of potential IP addresses on the network
• Display the IP address and MAC address for any that are found on an LCD display.
Prerequisites:
• Familiarity with Flowcode.
• Knowledge of the LCD display component.
Learning outcomes:
• MAC and IP address structure
• The structure of the Ethernet framework, which underpins all the other TCP/IP protocols.
• The datagram principle, where data inside a message may itself be a message.
• The process of sending, receiving and matching bytes.
Page 27 of 79
EB921 TCP/IP Solution Teachers’ notes
Exercise 1 objective:
• To build a program that can scan a range of potential IP addresses on the network and display
the IP address and corresponding MAC address for any that are found on an LCD display.
The receiving and displaying parts of the program will be contained in the main send message loop.
In order to simplify matters we will search only a certain range IP addresses [Link] to
[Link]. This means we only need worry about the last IP address byte which will simplify the
program. Actually there is another trick here as well. This range of addresses is traditionally reserved
for systems on the same local network or domain, which makes life much easier for us as we are much
more likely to get a response. They are also non-internet addresses so we do not need to worry about
accidentally trying to communicate to some far away machine.
Page 28 of 79
EB921 TCP/IP Solution Teachers’ notes
ARP Request
Ethernet header:
xxxxxxxxxxxx (destination address – out MAC)
xxxxxxxxxxxx (source address – their MAC)
Send ARP
0806 (type – ARP)
Request
ARP packet:
0001 (hardware type - ethernet)
0800 (protocol type – IP)
Check for ARP 06 (hardware size)
response 04 (protocol size)
0002 (operation – ARP response)
xxxxxxxxxxxx (source address – their MAC)
xxxxxxxx (source IP – their IP)
ARP xxxxxxxxxxxx (dest address – our MAC)
response No xxxxxxxx (dest IP – our IP)
received?
No
Timeout?
Yes
xxxxx indicates data that is either unknown or project
specific data that needs to be set up by the user
Display ARP
response details
Yes
Increment IP
address
Until end IP
address reached
End
10.3 Initializing
The first step is the standard initialization stage where you set up the components and variables.
• Initialize the TCP_IP component
• Initialize the LCD Display
• Initialize any variables – e.g. IP address Min, Max and starting values
Add an ‘Initialize’ macro to the beginning of your program to initialize the TCP_IP component, and a
‘Start’ macro for the LCD as well.
To send an Ethernet datagram you need to create a MAC socket to send it on. Add a
Create_MAC_Socket macro with the parameters set to promiscuous = 0, broadcast =0, error = 0. (You
don’t want to listen to any other traffic on the network, only messages sent to this node.)
Page 29 of 79
EB921 TCP/IP Solution Teachers’ notes
Set up a return value such as RETVAL to check for a successful connection. If it fails you can then error
trap it and inform the user that there has been a problem and end the program.
Ethernet header
Explanation Bytes Data for exercise
Destination The destination MAC address. 6 [Link].255.255
Using the MAC broadcast address
[Link].255.255 will pass the
message to all MAC devices on the Local
Area Network.
Source The MAC address of the sending device. 6 Use Tx_sendmynmac
Available in the TCP_IP component
property page.
Type The operation type 2 ARP = 8, 6
ARP datagram
Explanation Bytes Data for exercise
Hardware type: The type of hardware used. 2 0,1
generally this will be an Ethernet
connection, value 0x0001
Protocol type The type of protocol used. 2 0, 8
IP = 0x0008.
H/W adjustment The Hardware length is the length of the 1 6
length hardware identifier, in this case 6 for the 6
byte MAC address.
Protocol The Protocol length is the length of the 1 4
adjustment length protocol identifier, in this case 4 for the 4
byte IP address.
Operation The operations value that we will be using 2 0, 1 for request
are 0,1 for an ARP request, and 0,2 for an
ARP reply.
Page 30 of 79
EB921 TCP/IP Solution Teachers’ notes
Sender hardware The MAC address of the sending hardware 6 Use Tx_sendmymac
address device.
Sender IP The IP address of the sender. 4 Use Tx_sendmyip
Available on the component properties
page.
Target hardware Needs to be filled in, but is ignored by the 6 [Link].0.0
address receiving device.
Target IP address: The IP address that we wish to check for. 4 Either entered manually,
or set as variables e.g. a 4
byte array if the values
may change.
Once we have the data figured out we can send the message. The process of sending a message is as
follows:
• Tx_start (channel)
• Tx_sendbyte(channel, byte)
Needs repeating until all the data is sent.
Note that Tx_sendmymac and Tx_sendmyip can be used to send the MAC address and IP
address.
• Tx_end (channel)
Used to finish the data transmission.
Data padding and the checksum, are handled automatically by the TCP_IP component so can be
ignored.
Depending on issues such as network lag, or the speed at which a node process requests the responses
may not arrive in the order that the requests were sent.
If the node is trying to send a message of its own it may also contact our node with an ARP request of
its own. Something we will need to check for.
The first step is to check that for incoming data using the Rx_data_available macro. Remember that all
Ethernet communications are on channel 0.
The next step is to determine if it is an ARP message. We can do this by checking the Ethernet header
to see if the type matches up as an ARP message type. We can skip over any preceding data until we
get to the bytes that we wish to match. The macros Rx_skipbytes and Rx_match2bytes, Rx_match4bytes
and Rx_match6bytes can be used to move to and match the required data.
Page 31 of 79
EB921 TCP/IP Solution Teachers’ notes
Ethernet header
Bytes Skip read or match Notes
Destination 6 skip
Source 6 skip
Type 2 Match for ARP – 8, 6
Once we have determined it is an ARP message we can go through until we reach the operation bytes
which we can test to see if the message is an ARP reply. If so we can go through the rest of the
message and extract the MAC address and IP address. Once we have the data we need we can stop at
that point. We don’t need to read in the whole message.
ARP datagram
Bytes Skip read or match Notes
Hardware type 2 Skip
Protocol type 2 Skip
H/W adjustment 1 Skip
length
Protocol 1 Skip
adjustment length
Operation 2 Match for ARP reply – 0, 2
Sender hardware 6 Read in and display The MAC address we
address are looking for
Sender IP address 4 Read in and display The IP address that
sent the response
Target hardware 6 Skip – Actually we can stop here as we don’t
address need any more data.
Target IP address 4 Skip
Note that we get both the MAC address and the IP address. This is because we can’t assume that the
response is from any specific IP address, such as the last one we messaged. Due to network traffic, and
different device response speeds it could potentially be any of the IP addresses we previously
messaged. Or it could be an ARP request from another node on the network trying to find our MAC
address. Also if two machines have the same IP address we could receive two responses from the IP
address, but with different MAC addresses for the different nodes.
Once we have collected all the data we need from the message we will need to clear the data buffer to
allow the next message to come in using Rx_flush_data.
10.6 Timeout
On a slow or busy network the program may be able to respond much faster than the network. So we
need to be able to wait for a response.
Also our request may get ignored or lost, especially if the address we sent to doesn’t exist. So we need
to decide on a reasonable time span to wait before we decide that to move on and try the next address.
Page 32 of 79
EB921 TCP/IP Solution Teachers’ notes
loop by setting a starting address and checking for when it has reached an end address. A handy range
to check is from [Link] to [Link] as this particular IP range is reserved for nodes on the
same network, which is what we mainly want to check.
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 33 of 79
EB921 TCP/IP Solution Teachers’ notes
IP layer
The IP layer is at the Network level of the OSI model where communications between nodes is the key,
not communication between physical devices. A message may be required to be sent via a number of
MAC devices in order to reach the final destination. The IP layer provides the stamped addressed
envelope for network transport in the form of an IP address. The IP address is normally a four byte
code such as [Link]. The IP address gives network layer software and hardware such as routers
the information they need to send the message to the correct recipient node. Other information is
passed as well that the receiving software can use to determine where the message originated from, and
what kind of message it is.
The website addresses that we commonly used, such as [Link] are actually IP
addresses in disguise. TCP/IP protocols such as DNS are used to retrieve the numeric IP address from
the non-numeric values we give them. This is due to the human mind being better able to remember
words than numbers.
The IP datagram (derived from Telegram no doubt, adding to the mail system metaphors) is nestled
inside an Ethernet frame to allow the physical sending of the message onto the network. The IP
datagram contains a header file and a data packet. Just as the IP datagram (the envelope) is tucked
inside an outer wrapper Ethernet frame, the data section is in itself a message (the letter itself). This
message can be in a number of different formats e.g. TCP, UDP, and ICMP etc.
IP header
Description bytes
Version and Header Two 4-bit values combined into one byte 1
length For this course we will be using IP version 4.
The Header length is measured in 32 bit words. Normally this
is 5 words.
The normal value would thus be 0x45.
Type of Service Sets the priority for the datagram. Can normally be ignored and 1
Page 34 of 79
EB921 TCP/IP Solution Teachers’ notes
set to 0.
Total length Total length of the datagram including both header and data. 2
Fragmentation Identifier Used to aid fragmentation (i.e. breaking up messages too large 2
for one datagram).
We will not be covering fragmentation here, so can be set to 0.
Fragmentation offset Used to aid fragmentation (i.e. breaking up messages too large 2
for one datagram).
We will not be covering fragmentation here, so can be set to 0.
Time to live (seconds) Messages can only survive for a certain amount of time of the 1
network. This value is decreased during transit by the routers
until the message is finally discarded.
A good default is 100 seconds.
Protocol Identifies the protocol of the message contained in the data 1
section.
Possible values used to indicate which protocol is being used
include:
• ICMP = 1
• TCP = 6
• UDP = 17
Checksum A checksum value for the IP header. 4
Normally you will need to calculate this, as it all gets handled
by the TCP_IP component, however should you need to
generate the checksum manually you can use the following
process.
1) Byte swap the header
2) Pad with 0 if an odd length
3) Clear checksum value
4) Sum the 16 bit header words
5) Put one’s complement into checksum
Source IP address The originator’s IP address. 4
Destination address The IP address of the destination node. 4
Options Various options are available for the IP header. We will not be 0-40
using any options in this course, so this section can be safely
ignored for now.
Page 35 of 79
EB921 TCP/IP Solution Teachers’ notes
ICMP is commonly used to check connections with other computers. This is known as ‘pinging’ as it
works in the same way as the sonar ‘ping’ sent out by submarines. If it hits a target an echo will return
which can be picked up and examined.
ICMP datagram
Description bytes
Type Details the type of response or request being made. 1
Uses the following types:
• 0 Echo reply
• 3 Destination unreachable (error code)
• 8 Echo request
Page 36 of 79
EB921 TCP/IP Solution Teachers’ notes
The basics are that an ICMP message will receive an ICMP reply which can then be examined to see if
there were any errors, and if so which ones.
For example sending an ICMP message to a node with an unreachable port would generate a respond
with Type = 3 (Destination unreachable) and Code = 4 (Port unreachable). As you can guess getting
this kind of information is invaluable for network debugging.
Page 37 of 79
EB921 TCP/IP Solution Teachers’ notes
Note that if the datagram being sent has its own header, such as with ICMP, you will need to provide
the header information yourself as that is part of the data being sent via IP mode.
We can ping the internet board from the PC to see if we can get a reply from it.
Ping is simple to use. Simply open up a Command prompt (Run CMD) and type Ping <IP address
to ping> e.g. Ping [Link]
Page 38 of 79
EB921 TCP/IP Solution Teachers’ notes
The address will be pinged and the resulting timing data displayed.
We can use Ping to test our program. Simply ping the IP address you set for the TCP_IP component
([Link] by default). If all goes well it should get a very fast response time.
Page 39 of 79
EB921 TCP/IP Solution Teachers’ notes
Exercise objective:
• To ping another node to see if we get a response, hence can find it on the network.
Prerequisites:
• Knowledge of the MAC/Ethernet layer
Learning outcomes:
• Structure of an IP Datagram.
• Sending IP messages.
• Receiving IP responses.
• Reading data from the IP message.
Page 40 of 79
EB921 TCP/IP Solution Teachers’ notes
Exercise 2 objective:
• To ping another node to see if we get a response, hence can find it on the network.
Page 41 of 79
EB921 TCP/IP Solution Teachers’ notes
For this example we will be sending an ICMP datagram (protocol value of 1) on channel 0, and wish to
send and receive, so we will turn broadcast on (value set to1).
ICMP datagram
Description bytes Value to use in
exercise
Type Details the type of response or request being made. 1 8
Uses the following types:
• 0 Echo reply
• 3 Destination unreachable (error code)
• 8 Echo request
However, when replying to a Ping request you will not be so lucky and will need to create checksums
for your replies. The checksum code has been put into a convenient macro for you, which can be found
in the “Flowcode\TCP_IP\Examples” folder. Otherwise you will need to create your own
implementation of the checksum generation.
Page 42 of 79
EB921 TCP/IP Solution Teachers’ notes
Once again this follows the familiar pattern that we used with Ethernet packets.
Page 43 of 79
EB921 TCP/IP Solution Teachers’ notes
The types of response we are looking for are a Ping reply (type = 0), or a Ping request (type = 8). The
third option is Network unreachable (type = 3), in case we can then look at the error code value to see
what kind of error was generated. Fortunately this is the very first byte in the buffer, so we can check it
straight away.
Use Rx_readbyte to get the type value. You can also use a second Rx_readbyte to get the error code if
needed.
We will be sending a Ping echo with no error code do the first two bits will be 0, 0.
The next two bytes will be the two checksum bytes, which we will need to calculate.
The rest of the message is an echo of the ping message that we received, including the Identifier and
Sequence numbers and the data. We can reset the buffer, skip the first four bytes (type, code and the
two checksum bytes) and go through reading bytes and sending them back. We need to know how long
the data is though to be able to do this. Fortunately the IP header stores the data length for us. We can
use Rx_readheader(0,1) (channel 0, index 1) to retrieve the data length. Don’t forget that we have
already got the first four bytes though so the final check figure needs to be 4 less. (There is a second hi
byte for the amount of data, but Ping data is generally quite small so we shouldn’t need to worry about
it.)
With Ping you can verify IP addresses, useful for a multitude of tasks.
With a bit of timing code you can time or monitor connections – latency being a big issue in internet
networking.
There are a number of error codes that can be returned with ICMP. These could form the basis of an
expanded error checking project.
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 44 of 79
EB921 TCP/IP Solution Teachers’ notes
15 UDP
UDP (User Datagram Protocol) is a method of sending data direct to a specific socket (see below).
UDP can be used as a direct communications protocol, where you send messages direct to a specific
application on a specific system.
15.1 Sockets
A socket is a combination of an IP address and a port. A port is an electronic pigeonhole that the
various applications on the system can scan for messages. When a message arrives at a port it is the
responsibility of the applications to notice the arrival and to respond to the message. If no application is
monitoring the port when a message arrives then that message will be ignored.
Applications can also monitor ports allowing you to communicate with them directly. Given a specific
port number and a specific IP address you can communicate with a specific application on a specific
node. This is useful for custom applications that need to communicate over the internet, such as online
games, or off site control and monitoring programs.
In UDP we send a signal to a specific port and sit back and wait. If all went well and the application
monitoring the port is configured to respond to incoming messages then the port will generate a
response which we will receive, if not then we will receive nothing – no error message or anything.
Unlike ARP and ICMP which generated responses UDP does not – unless you write an application that
sends one. This has lead to UDP being referred to as “send and pray” communications.
One thing UDP is useful for is to send custom data messages direct from one system to another.
The data passed will be raw data so you will need to implement your own system for dealing with the
data.
Some ports are normally reserved for specific protocols such as SMTP (port 25) or HTTP (port 80).
When dealing with known protocols such as SMTP this simplifies matters as we can connect to a
known reserved port rather than having to find out from the system what port we need to connect to.
What ports are used can be changed but this would be unusual, and would be done for specific reasons
such as security issues. In such cases you may need to speak to the Network Administrator to find out
what ports are being used.
Page 45 of 79
EB921 TCP/IP Solution Teachers’ notes
UDP datagram
Description bytes
Source port The senders port address. 2
Destination port The port to be used at the destination. 1
Note that if no application is listening to that port then the message
may be lost.
Message length The length in bytes of the data packet 2
Checksum Checksum for the UDP packet. 4+
Handled automatically by the TCP_IP component in UDP mode.
Data The data for the UDP message. 0+
The data is sent as raw data. It is the responsibility of the sending
and receiving programs to process this data.
Note that like IP you will not normally need to create the header as it is handled automatically by the
TCP_IP component in UDP mode.
It is a blessing as you can decide what to send – ASCII text, integer values, data bytes for PICmicro
output etc. etc. How much data and in what order is up to you as well. Basically you send what you
want. If you wish to send custom messages UDP is the way to do it.
It is a curse in that you need to know what to expect when reading a message. Expecting and trying to
read in 20 integer bytes when instead you got the 5 byte ASCII text “Hello” could cause errors.
UDP has no type information, or any other kind of in built error checking. Any error checking needs to
be performed by the receiving application. As you are not in control of who sends a message to the
socket you have chosen you need to be aware that a message received may not necessarily be in the
expected format. It could for instance be from a completely different program with a completely
different custom message structure.
Some predefined sockets, such as Port 13, respond with a predefined message – e.g. a date/time string
but these are the exception not the rule, and even here the data format may vary from system to system
Page 46 of 79
EB921 TCP/IP Solution Teachers’ notes
If you need to respond or send UDP messages you need to set the destination socket that you wish to
send the message to. The Set_Destination macro allows you to set the channel, IP address and port
bytes of the target node. You can use the Rx_readbyte, Rx_skipbytes and Rx_match_XXX macros to
process
Once you have set a destination the Tx_sendbyte macro will send the data to that destination.
To change the destination to a different node use another Set_Destination macro with the new target
data.
Page 47 of 79
EB921 TCP/IP Solution Teachers’ notes
There is however one thing we need to know. Firstly, how much data is there?
We can get the Message length header item using the Rx_readheader macro. The data from item index
0 of the UDP header gives the high byte of the message length, and item index 1 gives the low byte of
the message length.
Using Rx_readheader we can put this into convenient variables such as SIZE_HI and SIZE_LO. Once
we have the message length we can loop through and Rx_readbyte it in ready to be dealt with.
Page 48 of 79
EB921 TCP/IP Solution Teachers’ notes
Once we have the data we need to deal with it. This will of course depend on what the data is (e.g.
sending ASCII text to the LCD as in the code snippet above). As UDP is custom data we will need to
know what the data is supposed to be. And we may need to check to see if the data is what we expected
and not an entirely different message.
Remember to flush the buffer once you have finished so that the next message can arrive.
There are some protocols that use UDP as a base, such as DHCP and DNS. To communicate with and
use these protocols you will need to look into details of how the data needs to be structured for them.
You may also need to find out what replies are sent, and how those replies are formatted.
Although relatively simple, the UDP protocol allows direct communication between two systems that
only need to be connected via a network, or linked to the internet. Physical distance then becomes
irrelevant. This comes at a cost though. You need to know the correct IP address and port details to be
able to send the message or it will simply disappear. Also there needs to be an application running on
the other end to read and respond to your message. If there is not, then nothing will happen.
Whilst this is fine for custom programs, it is not robust enough for global communications standards
such as SMTP email, or HTTP web pages. What we really need is something that is a bit more robust,
able to check for errors, able to respond to prompts or requests, and able to handle larger messages
automatically. This is where protocols such as TCP, with defined communication sequences, come in.
Page 49 of 79
EB921 TCP/IP Solution Teachers’ notes
Program objective:
• Use UDP to retrieve the time and date string from a PC.
• End if no response received after a ‘timeout’ period
Prerequisites:
• Knowledge of the MAC/Ethernet layer
• Knowledge of the IP layer
Required Information
• IP address of target PC
Learning objectives:
• Structure of a UDP Datagram
• Sending UDP messages
• Receiving UDP messages
• Preset socket responses
Page 50 of 79
EB921 TCP/IP Solution Teachers’ notes
A socket is required for the UDP connection. This can be on any port, but you should be aware of and
avoid using preset sockets such as Port 25, the SMTP port.
Start
Create UDP
layer socket for
Node A Target socket
Node A target is the Node B socket
Send message to
Time/Date
Socket UDP mesage
Message
Yes
received?
Display Time/
Date string
No
End
Page 51 of 79
EB921 TCP/IP Solution Teachers’ notes
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 52 of 79
EB921 TCP/IP Solution Teachers’ notes
19 TCP
To the general user TCP is what brings in the email message, or the HTML page. TCP is often thought
of as the code that these programs use. Which in one respect it is (as that’s the data that it carries), but
in another it is not. TCP is the process of controlling the transmission of that data. To TCP the data is
irrelevant; it’s the sending that counts. It’s the applications that pick up the data from TCP that care if it
is email or HTML.
Preset sockets are used extensively in TCP. Email applications will listen in on one port, HTML
programs on another. FTP and other programs will scan other ports. If you want to you can even build
a custom program to scan a particular port and send custom data to it using TCP.
IP header
Description bytes Notes
Source port The port that the sending TCP socket is 2
connected to.
Destination port The destination port to which the message will 2
be sent.
Sequence number Used with fragmentation to aid reassembly of 4
the datagram.
Acknowledgement Used with fragmentation to inform the sender of 4
number successful reception of the datagram.
Header length Length of the header in bytes. 1
Unused Unused. Reserved for expansion. 1
Flags Used to store bit flags for FIN, ACK, SYN, 1
Reset and Push.
Window The size of the buffer for incoming messages. 2
Checksum A checksum value for the TCP header. 2
Urgent pointer The IP address of the destination node. 2
Options and padding Various options are available for the TCP 4
header. We will not be using any options in this
course, so this section can be safely ignored for
now.
19.1 Connections
Connections are the key to understanding TCP. Using TCP revolves around controlling and
coordinating the connection. It is a bi-directional process, with the two parties engaged in a dialogue
rather than a send, reply, reply to the reply etc. system.
19.2 Acknowledgements
TCP is useful in that it will acknowledge the message as it arrives. In fact you can check, send, check,
send etc. in TCP to get the data sent whilst checking it has been received at the same time.
Page 53 of 79
EB921 TCP/IP Solution Teachers’ notes
Some systems such as SMTP requires an active dialogue with data sent in distinct steps with
acknowledgments sent at specific stages, and various tags or markers sent to distinguish parts of the
data being sent.
19.3 Fragmentation
Large amounts of data can be easily sent using TCP. TCP allows for messages to be split into
fragments that can be sent as IP datagram’s. TCP can then send the IP datagram's one by one (lockstep
method), in numbered blocks (block sequencing method), or by byte count (byte sequencing) where
both sides keep track of the amount of bytes sent and received.
The fragments are marked with a sequence number to aid reconstructing the message at the destination.
This allows fragments to arrive out of sequence without damaging the message data. It also aids in
checking for and resending lost fragments.
Page 54 of 79
EB921 TCP/IP Solution Teachers’ notes
The aim for an application is to move from CLOSED to an ESTABLISHED connection. The route
there depends on whether the connection is opened passively, or actively. Once a connection is
established the applications can communicate between each other until a FIN final closure message is
sent by one of the parties. Whereupon a closure sequence starts as the applications seek to move back
to the CLOSED state. At all stages there is the possibility of communications failure leading to a
RESET back to CLOSED.
To establish a connection a SYN message needs to be sent by the party initiating communications.
Once a SYN and an ACK have been received an ACK is sent and communications established.
Closing a connection is similar. A FIN is sent by the party wishing to end the connection. A FIN and an
ACK are expected in response, and a final ACK finishes it all of.
Whilst the state diagram seems complex at first following through the flow shows that the different
paths are just a matter of who initiates contact, and who terminates it and in which order they send the
required signal. The following sections demonstrate some of the main pathways through the state
diagram in action.
When an incoming SYN requests is received they send a SYN+ACK to indicate that they are ready to
communicate and move to the SYN RECVD state waiting for a final ACK before moving to
ESTABLISHED.
Page 55 of 79
EB921 TCP/IP Solution Teachers’ notes
Note that like IP and UDP you will not normally need to create the header as it is handled
automatically by the TCP_IP component.
Page 56 of 79
EB921 TCP/IP Solution Teachers’ notes
You can use the GetSocketStatus macro monitor the socket status to see if any external application is
trying to connect. The help file section on GetSocketStatus lists the various states and their return
values. Note that many of the variables relate to the various states in the state diagram (the others
mostly being concerned with forms of data transfer). The three most important states for monitoring are
SOCK_CLOSED – value 0, SOCK_ESTABLISHED – value 6 and SOCK_CLOSE_WAIT – value 7.
Once you have finished with the TCP connection you need to actively close it down. Call the
TCP_Close macro to close the connection. TCP_Close will handle the various FIN and ACK messages
that are required to close the connection
If the connection needs to be closed by the receiving application it will transmit a FIN message which
will put your application’s socket into the SOCK_CLOSE_WAIT state. You can monitor the socket
status using GetSocketStatus. Once SOCKET_CLOSE_WAIT is detected you should call the
TCP_Close macro to close the connection.
The SMTP response messages tell you to end the email data with the <CRLF>.<CRLF> message tag
i.e. a full stop on a line on its own. This would need to be sent as characters 13, 10, ‘.’, 13, 10.
Another problem character is the “ quote character. The quote character is used by Flowcode to
distinguish between strings e.g. “Hello world” and variables e.g. COUNT. So we can’t send the “
character as it will confuse Flowcode. Instead we need to send the ASCII code for “, which is ASCII
character code 34.
To communicate successfully with TCP applications it is necessary to know what these sequences are,
what responses to expect and what error codes will be sent. Some, such as an HTTP GET request can
Page 57 of 79
EB921 TCP/IP Solution Teachers’ notes
be a simple response. Others such as SMTP may require a number of steps in the sequence with
specific responses being required or being sent at various stages.
It is the understanding of communications sequences that will unlock TCP applications. And it is the
sequences that we will need to look at in the TCP exercises and examples.
Page 58 of 79
EB921 TCP/IP Solution Teachers’ notes
Program objective:
• Send HTML data when a HTPP GET request is received.
Prerequisites:
• Knowledge of the MAC/Ethernet layer
• Knowledge of the IP layer
• You will need PC with an internet browser connected to the network in order to view the
HTML page.
• A network traffic analyzer will also be useful for this particular task to aid in debugging the
data being sent and received.
Required information
• HTML code to be sent.
The following is a sample fragment of HTML that you can send:
HTTP/1.0 200 OK
Content-type: text/html
<html>
<head>
<title>TCP_IP Comp Web page</title>
</head>
<body>
<b>Hello World</b>
<p>How are you today?</p>
</body>
</html>
Learning outcomes:
• Structure of a TCP Datagram.
• TCP state diagram
• Create a passive listening TCP connection
• Sending TCP messages.
• Receiving TCP responses.
• Responding to a message.
• The structure of the GET request
• Basic HTML code
Page 59 of 79
EB921 TCP/IP Solution Teachers’ notes
22.1 Prerequisites
You will need PC with an internet browser connected to the network in order to view the HTML page.
To view the HTML you will need to point your browser at the page on the node. Open up the browser
and go to the IP address that you set up for the TCP_IP component ([Link] by default). The
default page will be sent for all requests so we do not need to worry about the page name.
HTTP/1.0 200 OK
Content-type: text/html
<html>
<head>
<title>TCP_IP Comp Web page</title>
</head>
<body>
<b>Hello World</b>
<p>How are you today?</p>
</body>
</html>
The first two lines are a HTTP header to inform the browser application of the format and type of
message being sent. The rest of the data is the HTML code for the web page. (HTTP header
information and HTML code tutorials can be found on the internet.)
We need to break up the HTML code to put it into the TCP datagram.
We will need to send the character codes 13 and 10 at the end of each line for the CRLF return key
ASCII values. (For your own HTML code other ASCII character codes, such as ASCII 34 for
quotation marks, may also be required depending on your HTML code.)
Page 60 of 79
EB921 TCP/IP Solution Teachers’ notes
Start
TCP socket
Initialise [Link] (IP address)
0, 80 (Port – hi and lo bytes
Port 80 is the default
HTTP port address)
Create TCP
layer socket for
Node A
Repeat
Check
socket for
incoming
message
<html>
<head>
Is it a ‘GET’
Yes <title>TCP_IP web page</title>
request?
</head>
No <body>
Send HTML page
<b>Hello World</b>
as raw data
No <p>How are you today?</p>
</body>
</html>
forever
End
We are not initiating communications so we can use passive mode with TCP_Listen. The socket can
then be checked using Rx_data_available to see if a request has arrived that needs responding to.
Rx_match4bytes can be used to check if this is indeed a “GET” message. (Note that we need to check
for the space as well to make the four characters needed for the macro. A small thing, but one so easily
overlooked.)
Page 61 of 79
EB921 TCP/IP Solution Teachers’ notes
As we are sending the same page for all requests we can ignore the page request part of the GET
request for this program.
HTTP/1.0 200 OK
Content-type: image/gif
FF006735BBCC234788…….. etc.
Page 62 of 79
EB921 TCP/IP Solution Teachers’ notes
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 63 of 79
EB921 TCP/IP Solution Teachers’ notes
Program objective:
• Retrieve HTML data with a HTPP GET request.
• Display the incoming data on the LCD display
Prerequisites:
• Knowledge of the MAC/Ethernet layer
• Knowledge of the IP layer
Required information
• IP address of the server for requesting the page
Learning objectives:
• Structure of a TCP Datagram.
• TCP state diagram
• Creating a TCP connection
• Sending TCP messages.
• Receiving TCP responses.
• Responding to a message.
• The structure of the GET request
Page 64 of 79
EB921 TCP/IP Solution Teachers’ notes
24.1 Prerequisites
You will need a Server capable of sending the page that is requested. You may wish to test the page is
available in an internet browser. A simple page is preferred as a large complex page with multiple parts
and images may be too much for the basic program to handle.
A Sever is simply a system that is capable of ‘serving up an HTML web page’ when requested. The
previous exercise – Sending HTML using HTTP is an example of a rather basic server. Although
generally Servers are large sophisticated computer systems that perform a myriad of other network
tasks as well.
Displaying the data is needed to show that we have indeed received the web page. However what data
to display is open for choice. For example:
• The data can be displayed as received allowing it to overflow the LCD display.
• A specific amount of data can be displayed e.g. enough to fill the LCD.
• A specific tag or piece of text can be searched for and a specific piece of HTML text extracted
from the code.
Page 65 of 79
EB921 TCP/IP Solution Teachers’ notes
Start
Initialize
TCP socket
Repeat
Check for
incoming
mesage
HTTP/1.0 200 OK
Content-type: text/html
HTTP
Message Yes <html>
arrived? <head>
<title>TCP_IP web page</title>
Retrieve </head>
No
HTML data <body>
<b>Temperature</b>
<p>23 deg. Celsius </p>
</body>
</html>
Process and
Display
HTML data Example display
Temp = 23 deg. C
forever
End
To receive a page of HTML you need to request the page that you want from the server with a GET
request with page name, and the HTTP version (we can use HTTP/1.0 for this). The GET request is
Page 66 of 79
EB921 TCP/IP Solution Teachers’ notes
followed by a blank line, so we will need to CRLF to the next line and CRLF again to produce the
blank one.
Once the Server receives the GET command it will start sending the data.
At this point we need to start checking for incoming data and read it in when it arrives. We may not be
able to store all the data due to the relatively small size of the PICmicro’s memory, so we will need to
work through it and either retrieve the data there and then and display it, or do whatever processes we
need to do with it, before we move onto the next batch of incoming data. If the incoming HTML data is
particularly large it may arrive in more than one message.
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 67 of 79
EB921 TCP/IP Solution Teachers’ notes
Program objective:
• Create a TCP connection.
• Open a structured dialogue with the mail server.
• Error checking dialogue responses.
Prerequisites:
• Knowledge of the MAC/Ethernet layer
• Knowledge of the IP layer
• Knowledge of TCP (as gathered from the previous TCP examples)
Required Information
• IP address of SMTP email Server
• Useable email address on the network that can be used to check the message.
Learning outcomes:
• TCP connections
• Performing structured TCP dialogues
• Error checking responses
• SMTP data formatting
Page 68 of 79
EB921 TCP/IP Solution Teachers’ notes
• HELO [System name] – an introduction message to get the message sequence started.
Note: This is correct it is HELO not HELLO. All the sequence dialogues start with a four
character word (except for ‘.’).
• MAIL FROM:<me@[Link]> - the address the email is being sent from.
• RCPT TO:<me@[Link]> – the recipients email address.
• DATA – a marker to indicate that you are ready to send the [Link] will be followed by the
message text itself.
• . – a single full stop on a line of it’s own. Used to indicate that the message data has been
sent.
• QUIT – a message to terminate the process.
Page 69 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 70 of 79
EB921 TCP/IP Solution Teachers’ notes
From:me@[Link]
To:you@[Link]
Subject: test
X-Mailer: Matrix SMTP
Notice how the From and To addresses are added in even though they were sent to the server as part of
the connection and acknowledgement process. There are a lot more header items that can be added as
well, but the above should suffice for basic messages. For more details on other header items you can
check for SMTP protocol details on the web.
SMTP messages are usually sent to Port 25 so you will need to set this up in the TCP_Connect macro
(dst_port_hi = 0, dst_port_lo = 25)
Next you need two valid email addresses: a ‘From’ email address and a ‘To’ email address. The ‘To’
email address definitely needs to be a valid email address that you have access to otherwise you will
not be able to receive the emails to test and debug the program.
The From email address can be a spoof or invalid test email address, however items such as firewalls
may perform checks and reject such emails. It is easier to set up a testing email address if this is
possible.
The only issue at this stage is getting the sequence right. By now you will have the knowledge and
experience to create the code required for the actual sending and receiving of messages.
With SMTP we are no longer concerned with sending just a message; we are now having dialogues and
negotiating communications.
The SMTP response messages tell you to end the email data with the <CRLF>.<CRLF> message tag
i.e. a full stop on a line on its own. This would need to be sent as characters 13, 10, ‘.’, 13, 10.
Another problem character is the “ quote character. The quote character is used by Flowcode to
distinguish between strings e.g. “Hello world” and variables e.g. COUNT. So we can’t send the “
character as it will confuse Flowcode. Instead we need to send the ASCII code for “, which is ASCII
character code 34.
Page 71 of 79
EB921 TCP/IP Solution Teachers’ notes
Note that properties, macro parameters and variable values etc. were set up for use with our network
and may require changing to match your own network or system configuration.
Page 72 of 79
EB921 TCP/IP Solution Teachers’ notes
Program objective:
• Create two Nodes which will respond to communication by sending the communicator a reply
message.
• Node A
o Can initiate when ‘Send button’ is pressed
o Will respond to a signal by sending a response
o [Link]
o Port 5
o Message: “Hello world”
• Node B
o Can block contact when ‘Off button’ is pressed
o Will respond to a signal by sending a response
o [Link]
o Port 10
o Message “Hi globe”
Prerequisites:
• Knowledge of the MAC/Ethernet layer
• Knowledge of the IP layer
Learning objectives:
• Structure of a UDP Datagram
• Sending UDP messages
• Receiving UDP messages
• Responding to a message
Page 73 of 79
EB921 TCP/IP Solution Teachers’ notes
If you wish to use Network traffic monitoring software you will need either a hub or two connection
points onto the network.
Page 74 of 79
EB921 TCP/IP Solution Teachers’ notes
Page 75 of 79
EB921 TCP/IP Solution Teachers’ notes
Our project is to design and implement a firewall application. You will need to create a program that
acts as an intermediary between two Ethernet boards, deciding if a message should be allowed to pass
through or not.
One board connected to the network, and the other connected to the protected PC. You can then create
an application that monitors both and decides whether to pass the data on to the other board or not.
We will leave this up to you to decide what to block – specific IP addresses, ARP requests, Emails etc.
Bear in mind that the PICmicro has limited memory available so it may be best to keep it simple at
first, and maybe expand the application later once it is working.
To help you get started we have included an example flowchart for a basic firewall system that passes
the Ethernet messages between two systems.
Page 76 of 79
EB921 TCP/IP Solution Teachers’ notes
Start
Packet size
Initialise A Start Packet status
<ProcessPacket> MAC source
MAC destination
Protocol
IP source
Initialise B Read IP destination
incoming Port source
data Port destination
properties Etc...
Read
Repeat
incoming
forever
buffer
Data Write
received outgoing
on A? buffer
Process
Packet
(A to B)
Until packet
transfer complete
Data
received
on B?
Send
buffer
Process
Packet
(B to A)
Flush incoming
buffer
Repeat
forever
End
<ProcessPacket>
End
Page 77 of 79
EB921 TCP/IP Solution Teachers’ notes
30 Further work
There is a lot more to learn about TCP/IP, both about the process of sending and receiving messages,
and about the data messages that can be sent.
30.1 Fragmentation
There are issues of fragmentation, where messages require breaking into smaller parts, or fragments,
and also require reassembly at the other end. This is largely irrelevant for the PICmicro as the relatively
small memory of the PICmicro will most likely be a more immediate factor. Basic fragmentation issues
are also handled automatically by the internet board. However using memory chips, or using the
PICmicro as a transfer conduit, may create files sufficiently large for fragmentation to be an issue.
Should you wish to look into other TCP message formats, such as POP3, FTP or TELNET you will
need to look for details on how to structure the data, and what request/response dialogues are required.
Page 78 of 79
EB921 TCP/IP Solution Teachers’ notes
32 Glossary
32.1 Acronyms
ARP – Address Resolution Protocol
DHCP – Dynamic Host Configuration Protocol
DNS – Domain Name Servers
FTP – File Transfer Protocol
HTML – HyperText Markup Language
HTTP – HyperText Transfer Protocol
ICMP – Internet Control Message Protocol
IP – Internet Protocol
MAC – Media Access Control
POP3 – Post Office Protocol 3
SMTP – Simple Mail Transfer Protocol
TCP – Transmission Control Protocol
UDP – User Datagram Protocol
URL – Universal Resource Locator
32.2 Glossary
Firewall – a security monitoring system that’s helps prevent unauthorized messages getting through to
the node. Normally software based but can also include hardware based firewalls.
Hub – A network connection point. Messages received are sent to all other connections on the hub.
Hubs are non-intelligent and simply pass incoming messages on with no filtering.
Node – A system on the network with an IP address and a MAC address, be it a PC, a Unix server, or
an E-blocks internet solution etc.
Router – A device that can accept TCP/IP messages and pass them on to the next device in the path
between the sender and the recipient nodes. Routers are capable of intelligently assessing network
problems and blockages and re-routing messages depending on the network conditions.
Switch – Similar to a hub but with intelligent filtering which stops messages being sent to connections
that the message is not for. Not recommended for use with Network traffic analyzers as they prevent
general network traffic messages from getting through to the analyzing node.
Page 79 of 79