Skip to content

Instantly share code, notes, and snippets.

@seansummers
Last active September 15, 2015 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seansummers/597aa9a4768422987a3a to your computer and use it in GitHub Desktop.
Save seansummers/597aa9a4768422987a3a to your computer and use it in GitHub Desktop.
RFC1071 Internet Checksum -- gawk
#! /usr/bin/gawk
# RFC1071 Computing the Internet Checksum (in gawk)
# written by Sean Summers <seansummers@gmail.com> 2015-09-15 v0.1
#
# use '@include "internet_checksum.gawk"' to include in a script
function _ord_init(low, high, i, t) {
# creates _ord_ array for ascii lookup
low = 0; high = 127;
for (i = low; i <= high; i++) {
t = sprintf("%c", i);
_ord_[t] = i;
}
}
function internet_checksum(str, chunk) {
# checksum from a string and chunk size (by default 4)
# with chunk==2, this [should be] the RFC1071 Internet Checksum (haven't tested yet)
chunk = (chunk == 0) ? 4 : chunk;
size = length(str);
split(str, chars, "");
sum = 0;
for (i = 1; i <= size; i += chunk) {
cur = 0;
val = _ord_[chars[i]];
for (j = 0; (j < chunk) && ((i + j) <= size); j++) {
cur += lshift(val, 8 * j);
}
sum += cur;
}
return compl(sum);
}
BEGIN {_ord_init()}
@include "internet_checksum.gawk";
{
printf("Internet Checksum\nInput:\t%s\nValue:\t%d\n", $0 ,internet_checksum($0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment