#!/usr/bin/env awk
#
# Returns true if the destination port is equal to 'p' (int or hex)
# If 'p' is omitted, returns the destination port
#
# Parameters:
#   - [p] : the port number(s) to test (comma or semicolon separated)
#           (ranges may also be specified using a dash (see examples below))
#
# Dependencies:
#   - basicFlow
#
# See Also:
#   - port : source or destination port
#   - sport: source port
#
# Examples:
#   - tawk 'sport(80)' file.txt           # test for dest. port 80
#   - tawk 'sport("53;80")' file.txt      # test for dest. ports 53 or 80
#   - tawk 'sport("6000-6008")' file.txt  # test for dest. ports 6000, 6001, ... or 6008
#   - tawk 'sport("1-3;5;7-9")' file.txt  # test for dest. ports 1 to 3, 5, or 7 to 9
#   - tawk '{ print sport() }' file.txt   # print the destination port

@include "hdr"
@include "isnum"
@include "_validate_col"

function dport(p,        _dp, _i, _l, _ports, _rng) {
    _dp = _validate_col("dstPort", _my_dstPort)
    if (!p || (__PRIHDR__ && hdr())) return $_dp
    _dp = strtonum($_dp)
    if (isnum(p)) return (_dp == p)
    _l = split(p, _ports, /[,;]/)
    for (_i = 1; _i <= _l; _i++) {
        if (match(_ports[_i], /^(0x[[:xdigit:]]+|[0-9]+)-(0x[[:xdigit:]]+|[0-9]+)$/, _rng)) { # range
            if (_dp >= strtonum(_rng[1]) && _dp <= strtonum(_rng[2])) {
                return 1
            }
        } else if (_dp == strtonum(_ports[_i])) {
            return 1
        }
    }
    return 0
}
