Question

Checksum code in C

Asked by: erimay

Dear experts,

        I need to add a checksum to a frame that will be sent from client A to Client B thru protocol. Could someone please show me an example of checksum code to add a checksum to a frame before it is send, on client A side, and calculating the checksum for error detection on the receiver side (client B)?

Please reply asap.
Thank you.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-12-04 at 00:37:47ID20816121
Tags

checksum

,

code

,

c

Topic

C Programming Language

Participating Experts
5
Points
180
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. checksum function in c / c++
    hi, i need a fast function to calculate the checksum of a file. (similiar to the cksum shell command) thanx, ittay
  2. checksum
    How to find checksum of a file? any windows app is used for that? Can be writed in delphi sucha function?
  3. Checksum program
    Could anyone please provide me with a simple C program (or sources of any)to calculate the checksum over a string(input being a pointer to the string and the length of the string). I have to use it in another program (to manipulate IP datagrams) Thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sunnycoderPosted on 2003-12-04 at 00:42:48ID: 9873037

 

by: void_mainPosted on 2003-12-04 at 02:07:54ID: 9873304

Or you download the quake II source code from www.idsoftware.com and have a look into crc.c and crc.h. There is networking code for client/server too, but only if you download the full sourcecode (not the "game source")
I think that could help!

 

by: skypalaePosted on 2003-12-04 at 03:25:00ID: 9873593

Hi,

there are3 many algorithms calculating checksums. You only have to choose which will you use. One more thing you should think of. And it is what type of check code do you want to send. Will it only detect error? Or will it be able to correct an error? Or 2 or more errors? Every code is slightly different, but generally calculating the more self repairing codes takes more time, more memory and larger code to send. And if you check the code and you find out that there are more errors because of transmission than the code can repair, you have to ask for whole packet again. Especially if the error is in the code.

The most easy is simple checksum. Just take your packet byte by byte and add those bytes (never mind overflowing ... or you can XOR them). In the end you have a code. Reciever then adds every byte and if the sum is same as the last one the packet os OK. (In case of XORing, you process the code too and result must be 0). This code is very fast and efficient until you get 2 errors. If they appear and they are same (like one byte will be 1 bigger and other byte will be 1 lower), the code gives good result, but there are errors. in the trasmitted data. In that case you can enlarge the code to word or long, but the same thing may happen too.

The error repairing codes are slightly different. I can't remember how classis CRC works, but it has something to do with polynomial division, modulo of that. The code was quite complicated to calculate, but when checked (in case of error) it gave exact position of the error (as far as i remember, you can enlarge the code to check 2 or more errors)

...

The other self repairing code is quite simple and it checks for exact error position too. First arrange all your data into rectangle areas (i'll use 4x4 rectangles in my example)

so imagine data

1001010110000011

like this

1001
0101
1000
0011

now do the XOR on each line and on each column now you get this:

0110
--------
1001 | 0
0101 | 0
1000 | 1
0011 | 0

and return everything into linear again

data: 1001010110000011 col_codes: 0110 row_codes: 0010

so after every 2 bytes you send 1 byte of code. If you use larger rectangles, the relative size of code will be smaller, but it will catch less errors .. you decide what ratio you want. The reciever side does exactly the same and then it compares the codes. If there are differencies, (in case of one error) the positions of the differencies give you exact position (column, row) of bit changed.

same can be dane with bytes .. i'll write simple steps (includeng error)

packet :
1fe03a83b24573a1

rectangle:
1fe0
3a83
b245
73a1

coded recnagle:
e487
------
1fe0 | 0
3a83 | 2
b245 | 8
73a1 | f

coded packet:
1fe03a83b24573a1 e487 028f

........

recieved packed:
1fe03a83b44573a1 e487 028f

rectangle packet (coded)

e287
------
1fe0 | 0
3a83 | 2
b445 | e
73a1 | f

compare codes and find ERROR!!
2.column (sent code 4, calculated code 2)
3.row (sent code 8, calculated e)

2 XOR 4 -> 6
8 XOR e -> 6
seems, that codes are ok, error is in the packet. if the result differ, the error might be in the codes.

recieved value 4, error correction 6

4 XOR 6 -> 2

new value 2




Is it clear enough? I'm sure you don't need source. You can writye your own :)
S.

 

by: skypalaePosted on 2003-12-04 at 03:32:28ID: 9873626

Well. the example i've posted is not really using bytes, but half-bytes (nibbles). but you can easily modify it to bytes, words, whatever you want (and can XOR it).
S.

 

by: KdoPosted on 2003-12-09 at 06:55:11ID: 9904477

Hi erimay,

There's been no activity here for a few days and I'm feeling "talkative".

Checksums.  The word has been around a long time and has come to mean "a series of calculations on a dataset that offers reasonable protection against data change".  But the protection that it offers is often a false sense of security.

Some of the oldest checksum algorithms simply XOR all of the values in the dataset and produce a final result.  (One was shown earlier in this thread.)  While this does offer some protection over single bit changes, it no longer offers adequate data protection.  (The days when read/write errors or communications errors result in a single bit changing are pretty well behind us.)  Besides, there are so many calculcations that produce a single value, that a better algorithm was/is needed.

'A' = 0x41
'B' = 0x42
-----------
        0x03  Checksum using the XOR method.

If any one value in the region being checksummed is to change, the checksum value will also change.  (Simple algebra here.  A = B ^ C.  If two of the values are known, the third is also known.)

But if both values change, then the new checksum value may or may not be the original checksum value.

'E' = 0x45
'F' = 0x46
-----------
        0x03 Checksum using the XOR method.  The same as checksumming 'A' and 'B'

So a complete change of the data may not be caught, but if any one bit, or byte (including the checksum value) is changed then recalcuating the checksum will detect the change.  Anyone with malicious intent should be able change a value in the data and correctly adjust the checksum with little effort.

Clearly a better form of checksum calculation is required.  The next generation of checksum algorithms offered somewhat better security by performing two sets of calculations on the data and merging the result.  The oldest duel-calculation algorithm that I know of generated one result by an XOR of all of the data values.  It generated a second result simply by adding all of the bytes together.  The two results were then XORed to produce a final checksum.  But this too proved too little.

'A' = 0x41
'B' = 0x42
-----------
      0x003 Checksum value using XOR
      0x083 Checksum value using + (add)
-----------
      0x080 Final Checksum

But again the mathematics breaks down when you simply swap two bytes.  Algebra's basic rules of A+B=B+A and A*B=B*A are pretty hard to get around.

Not only is this pretty low hurdle for someone with malicious intent, it offers no protection over one of the most simple human errors -- transposing digits.  Transpose two digits when someone is entering a telephone number and the worst thing that happens is some yelling and screaming when you dial the wrong number at 4:00AM.  Transpose two digits when entering a Credit Card Number can be disastrous.  (Credit card numbers have very robust validity algorithms to protect against single digit change, side-by-side digit transposition, random digit transposition, and other data changes.)

Checksum algorithms generation 2.1 modified the addition half of the calculation by multiplying the character value by its position in the dataset.  Suddenly, it became much harder to randomly change data and adjust the checksum.

'A' = 0x41
'B' = 0x42
-----------
      0x003 Checksum value using XOR
      0x0C5 Checksum value using + (add)  0x41 * 1 + 0x42 * 2
-----------
      0x0C6 Final Checksum

'B' = 0x42
'A' = 0x41
-----------
      0x003 Checksum value using XOR
      0x0C4 Checksum value using + (add)  0x42 * 1 + 0x41 * 2
-----------
      0x0C7 Final Checksum

Many forms of checksums still exist today.  A Cyclic Redundancy Check is a modern version of a checksum.  It's more secure than any of the algorithm mentioned so far.  It's also more compute intensive since there a numerous calculations performed on each byte.  Still, for your application a simple and secure checksum algorithm should do just fine.

/*
  ChecksumRegion -- Calculate a checksum over a memory region
    Buffer - Start address of region to checksum
    Length - Number of bytes to checksum
*/

int ChecksumRegion (void *Buffer, int Length)
{
  unsigned char *Ptr;
  int   idx;
  int   XORValue;
  int   SUMValue;

  Ptr = (unsigned char *)Buffer;
  XORValue = 0;
  SUMValue = 0;
  for (idx = 1; idx <= Length; ++idx)
  {
    XORValue ^= *Ptr;
    SUMValue += (*Ptr * idx);
  }
  return (XORValue ^ SumValue);
}

Ok.  I guess that I'm over this 'talkative' mood this morning.

Good Luck with your program,
Kent

 

by: Big_Red_DogPosted on 2004-05-12 at 12:35:11ID: 11053195

Kdo forgot to advance the pointer in the buffer...

Here's the corrected code:

/*
  ChecksumRegion -- Calculate a checksum over a memory region
    Buffer - Start address of region to checksum
    Length - Number of bytes to checksum
*/

int ChecksumRegion (void *Buffer, int Length)
{
  unsigned char *Ptr;
  int   idx;
  int   XORValue;
  int   SUMValue;

  Ptr = (unsigned char *)Buffer;
  XORValue = 0;
  SUMValue = 0;
  for (idx = 1; idx <= Length; ++idx, Ptr++)
  {
    XORValue ^= *Ptr;
    SUMValue += (*Ptr * idx);
  }
  return (XORValue ^ SumValue);
}

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...