Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculate an Internet (aka IP, aka RFC791) checksum in C#
    primarykey
    data
    text
    <p>Interestingly, I can find implementations for the Internet Checksum in almost every language except C#. Does anyone have an implementation to share?</p> <p>Remember, the <a href="http://www.faqs.org/rfcs/rfc791.html" rel="nofollow noreferrer">internet protocol</a> specifies that:</p> <p>"The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero."</p> <p>More explanation can be found from <a href="http://mathforum.org/library/drmath/view/54379.html" rel="nofollow noreferrer">Dr. Math</a>.</p> <p>There are some <a href="http://www.faqs.org/rfcs/rfcresults.html?cx=012585674615115756003%3A0rnper8ld_o&amp;cof=FORID%3A11&amp;ie=UTF-8&amp;hq=more%3Arfc&amp;q=internet+checksum&amp;sa=Search+RFCs&amp;siteurl=www.faqs.org%2Frfcs%2Frfc1071.html#1192" rel="nofollow noreferrer">efficiency pointers</a> available, but that's not really a large concern for me at this point.</p> <p>Please include your tests! (Edit: Valid comment regarding testing someone else's code - but I am going off of the protocol and don't have test vectors of my own and would rather unit test it than put into production to see if it matches what is currently being used! ;-)</p> <p>Edit: Here are some unit tests that I came up with. They test an extension method which iterates through the entire byte collection. Please comment if you find fault in the tests.</p> <pre><code>[TestMethod()] public void InternetChecksum_SimplestValidValue_ShouldMatch() { IEnumerable&lt;byte&gt; value = new byte[1]; // should work for any-length array of zeros ushort expected = 0xFFFF; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); } [TestMethod()] public void InternetChecksum_ValidSingleByteExtreme_ShouldMatch() { IEnumerable&lt;byte&gt; value = new byte[]{0xFF}; ushort expected = 0xFF; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); } [TestMethod()] public void InternetChecksum_ValidMultiByteExtrema_ShouldMatch() { IEnumerable&lt;byte&gt; value = new byte[] { 0x00, 0xFF }; ushort expected = 0xFF00; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload