Friday, September 21, 2012

ENC28J60 - PSoC3 - Part 5 ICMP(ping)

So now that we know how packets will be actually sent(and received) with the ENC28J60,all we need to do now is build code on top of that,which creates and processes the packets to send(or receive).

We looked at ARP last time,so its Ping for this post.
The ping is the second most basic routine for any network device.You could say,that if a device replies to a Ping request,then its active.I wont go into the history and such,and will skip directly to the need-to-know stuff of things with implementing this.

So,why is Ping important to us,in this case? Well,its not really essential to our basic goal of an embedded webserver(or webclient).But,if youre building a network connected device,its convention that it should be able to answer to Pings(technically speaking,ICMP Echo Requests.) and ARP requests etc.Ping gives us an easy way to test if our chip is active on the network.

Our main focus then is to reply to ping requests.So,heres what a Ping Request might look like.

The layout of a ICMP packet

It will have an  Ethernet header(like ARP did.),then an IP(Internet protocol) header and the actual ICMP header part,(shown in pink above).

Heres what those structs look like for us.

Note that the IPhdr has an eth header inside it,so we'll use the '->' to access that level in the struct,since we'll be dealing with pointers to the structs.

We'll look into what we need to do to reply to a ping.So,when pinged from the connected computer(or any network equipment) our ENC28J60 should reply back.

What that means for us,is basically we'll get a packet in the ENC's buffer,in the above format.All we'll need to do is edit some fields,and we have a reply ready :-) So we dont really create the packet here,we just edit it.

So heres what we can start with,in our PingReply function

Swapping the MAC addresses is the first thing we need to do.We'll swap the IP Address fields in the IP header next.

The next important bit,is the checksum.I'll explain a little on how that works.Its basically a sum of the IP header taken in chunks of 16bits,and complemented.So,a series of 16 bit words,added up,and complemented(1s compliment) in the end.This is a very common function,and theres tons of documentation around this.I suggest you google that up.

With the checksum calculated,its ready to be sent :-)

So,when pinged,the PSoC will edit the packet it receives,and send it right back as a reply.Simple enough? It is.
Here, is our ENC28J60,and is my laptop.I know the ping times are high,but this isnt a bare ping application.Its doing a lot of other stuff,and clocked at only 24Mhz,so delay is expected.

Hooray! Its alive :-)

As usual,all the code is available on my github repo.Thats all for this post.

No comments:

Post a Comment