tcp

Wait for a Local TCP Port with Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python
import time
def waitForTcpPort(port, timeout=20, poll=0.1):
start = time.time()
with open('/proc/net/tcp','r') as f4, open(
'/proc/net/tcp6', 'r') as f6:
while True:
f4.seek(0)
f6.seek(0)
lines = f4.readlines()[1:] + f6.readlines()[1:]
sockets = map(str.split, lines)
listeners = [l for l in sockets if l[3] == '0A']
ports = [int(l[1].split(':')[1], 16) for l in listeners]
if port in ports:
break
time.sleep(poll)
if time.time() - start > timeout:
raise Exception("Timed out waiting (>%gs) for TCP port %d"
% (timeout, port))
if __name__ == '__main__':
import argparse
p = argparse.ArgumentParser()
p.add_argument('port', help='port to wait for', type=int)
args = p.parse_args()
waitForTcpPort(args.port)

Tcpdump: Shrink pcap File By Reducing Snaplen

I used tcpdump to capture some traffic, but then realized that I didn’t need any of the application layer payload, but just the headers. The problem was that I had already done the capturing, and I had these huge pcap files taking up the precious space on my machine. What I first tried was using tcpdump to read the file and dump it, with a smaller snaplen: tcpdump -s 96 -r in.cap -w smaller.cap. That does not seem to change the snaplen, however. The solution I found is to use editcap, as described here:
https://www.wireshark.org/docs/man-pages/editcap.html

The second example in the manual was what I was looking for. This did the trick:

1
editcap -s 96 big_in.cap smaller_out.cap