Last active
September 15, 2015 18:42
-
-
Save seansummers/597aa9a4768422987a3a to your computer and use it in GitHub Desktop.
RFC1071 Internet Checksum -- gawk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/gawk | |
# RFC1071 Computing the Internet Checksum (in gawk) | |
# written by Sean Summers <[email protected]> 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()} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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