# Buggy code
def _freebsd_remotes_on(port, which_end):
    """
    Returns set of ipv4 host addresses of remote established connections
    on local tcp port port.

    Parses output of shell 'sockstat' (FreeBSD)
    to get connections

    $ sudo sockstat -4
    USER    COMMAND     PID     FD  PROTO  LOCAL ADDRESS    FOREIGN ADDRESS
    root    python2.7   1456    29  tcp4   *:4505           *:*
    root    python2.7   1445    17  tcp4   *:4506           *:*
    root    python2.7   1294    14  tcp4   127.0.0.1:11813  127.0.0.1:4505
    root    python2.7   1294    41  tcp4   127.0.0.1:61115  127.0.0.1:4506

    $ sudo sockstat -4 -c -p 4506
    USER    COMMAND     PID     FD  PROTO  LOCAL ADDRESS    FOREIGN ADDRESS
    root    python2.7   1294    41  tcp4   127.0.0.1:61115  127.0.0.1:4506
    """

    port = int(port)
    remotes = set()

    try:
        data = subprocess.check_output(["sockstat", "-4", "-c", "-p {0}".format(port)])
    except subprocess.CalledProcessError as ex:
        log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
        raise

    lines = data.split("\n")

    for line in lines:
        chunks = line.split()
        if not chunks:
            continue
        # ['root', 'python2.7', '1456', '37', 'tcp4',
        #  '127.0.0.1:4505-', '127.0.0.1:55703']
        # print chunks
        if "COMMAND" in chunks[1]:
            continue  # ignore header
        if len(chunks) < 2:
            continue
        local = chunks[5]
        remote = chunks[6]
        lhost, lport = local.split(":")
        rhost, rport = remote.split(":")
        if which_end == "local" and int(lport) != port:  # ignore if local port not port
            continue
        if (
            which_end == "remote" and int(rport) != port
        ):  # ignore if remote port not port
            continue

        remotes.add(rhost)

    return remotes


# Traceback (CalledProcessError)
claudia ~ # salt claudia test.ping
ckstat: syntax error in port range
[ERROR   ] Failed "sockstat" with returncode = 1
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
CalledProcessError: Command '['sockstat', '-4', '-c', '-p 4505']' returned non-zero exit status 1
Traceback (most recent call last):
File "/usr/local/bin/salt", line 9, in <module>
load_entry_point('salt==2014.7.1', 'console_scripts', 'salt')()
File "/usr/local/lib/python2.7/site-packages/salt/scripts.py", line 241, in salt_main
client.run()
File "/usr/local/lib/python2.7/site-packages/salt/cli/__init__.py", line 187, in run
for full_ret in cmd_func(**kwargs):
File "/usr/local/lib/python2.7/site-packages/salt/client/__init__.py", line 584, in cmd_cli
**kwargs):
File "/usr/local/lib/python2.7/site-packages/salt/client/__init__.py", line 1212, in get_cli_event_returns
connected_minions = salt.utils.minions.CkMinions(self.opts).connected_ids()
File "/usr/local/lib/python2.7/site-packages/salt/utils/minions.py", line 444, in connected_ids
addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 897, in local_port_tcp
ret = remotes_on_local_tcp_port(port)
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 1053, in remotes_on_local_tcp_port
return _freebsd_remotes_on(port, 'local_port')
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 1000, in _freebsd_remotes_on
data = subprocess.check_output(['sockstat', '-4', '-c', '-p {0}'.format(port)])
File "/usr/local/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command '['sockstat', '-4', '-c', '-p 4505']' returned non-zero exit status 1
Traceback (most recent call last):
File "/usr/local/bin/salt", line 9, in <module>
load_entry_point('salt==2014.7.1', 'console_scripts', 'salt')()
File "/usr/local/lib/python2.7/site-packages/salt/scripts.py", line 241, in salt_main
client.run()
File "/usr/local/lib/python2.7/site-packages/salt/cli/__init__.py", line 187, in run
for full_ret in cmd_func(**kwargs):
File "/usr/local/lib/python2.7/site-packages/salt/client/__init__.py", line 584, in cmd_cli
**kwargs):
File "/usr/local/lib/python2.7/site-packages/salt/client/__init__.py", line 1212, in get_cli_event_returns
connected_minions = salt.utils.minions.CkMinions(self.opts).connected_ids()
File "/usr/local/lib/python2.7/site-packages/salt/utils/minions.py", line 444, in connected_ids
addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port']))
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 897, in local_port_tcp
ret = remotes_on_local_tcp_port(port)
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 1053, in remotes_on_local_tcp_port
return _freebsd_remotes_on(port, 'local_port')
File "/usr/local/lib/python2.7/site-packages/salt/utils/network.py", line 1000, in _freebsd_remotes_on
data = subprocess.check_output(['sockstat', '-4', '-c', '-p {0}'.format(port)])
File "/usr/local/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['sockstat', '-4', '-c', '-p 4505']' returned non-zero exit status 1

# Fixed code
def _freebsd_remotes_on(port, which_end):
    """
    Returns set of ipv4 host addresses of remote established connections
    on local tcp port port.

    Parses output of shell 'sockstat' (FreeBSD)
    to get connections

    $ sudo sockstat -4
    USER    COMMAND     PID     FD  PROTO  LOCAL ADDRESS    FOREIGN ADDRESS
    root    python2.7   1456    29  tcp4   *:4505           *:*
    root    python2.7   1445    17  tcp4   *:4506           *:*
    root    python2.7   1294    14  tcp4   127.0.0.1:11813  127.0.0.1:4505
    root    python2.7   1294    41  tcp4   127.0.0.1:61115  127.0.0.1:4506

    $ sudo sockstat -4 -c -p 4506
    USER    COMMAND     PID     FD  PROTO  LOCAL ADDRESS    FOREIGN ADDRESS
    root    python2.7   1294    41  tcp4   127.0.0.1:61115  127.0.0.1:4506
    """

    port = int(port)
    remotes = set()

    try:
        cmd = shlex.split("sockstat -4 -c -p {0}".format(port))
        data = subprocess.check_output(cmd)
    except subprocess.CalledProcessError as ex:
        log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
        raise

    lines = data.split("\n")

    for line in lines:
        chunks = line.split()
        if not chunks:
            continue
        # ['root', 'python2.7', '1456', '37', 'tcp4',
        #  '127.0.0.1:4505-', '127.0.0.1:55703']
        # print chunks
        if "COMMAND" in chunks[1]:
            continue  # ignore header
        if len(chunks) < 2:
            continue
        local = chunks[5]
        remote = chunks[6]
        lhost, lport = local.split(":")
        rhost, rport = remote.split(":")
        if which_end == "local" and int(lport) != port:  # ignore if local port not port
            continue
        if (
            which_end == "remote" and int(rport) != port
        ):  # ignore if remote port not port
            continue

        remotes.add(rhost)

    return remotes