The task:
Output the IP address under which the machine sends requests to 8.8.8.8 (there is no need to take into account NAT after the packet leaves the machine, you need an IP address with which the packet leaves the machine).
You need to write a bash script. As I understand it, you need to understand where we have a gateway on the local network.
At the moment, the following is ready:
use tcpdump - tcpdump -i any 'udp port 53'> whoIP - so the dump result with all requests for port 53 (that is, DNS) is saved to a file.
The file contains the following lines:
15: 09: 44.365818 IP 192.168.0.102.11996> 192.168.0.1.domain: 31675+ A? www.google-analytics.com. (42)
15: 09: 44.398267 IP 192.168.0.1.domain> 192.168.0.102.11996: 31675 7/0/0 CNAME www-google-analytics.l.google.com., A
then using the "Hellish" expression: cat whoIP | grep A? | grep -E -o '> + ([0-9] {1,3} [.]) {3} [0-9] {1,3}' | grep -E -o "([0-9] {1,3} [.]) {3} [0-9] {1,3}"
Its logic is as follows:
cat whoIP | grep A? - in the file we are looking for lines containing a request for name resolution. tcpdump marks such strings as A?
| grep -E -o '> + ([0-9] {1,3} [.]) {3} [0-9] {1,3}' - this regular expression searches for an IP address in ipv4 format. in the line we are looking for the following construction ">" ipv4 address "" - in tcpdump ">" means from whom to whom the request goes. We are interested in who.
| grep -E -o "([0-9] {1,3} [.]) {3} [0-9] {1,3}" - from the found fragment "to whom" we cut out only the address. This expression from previous differs only in the absence of "<"
In general, my algorithm is as follows:
1. Run tcpdump and redirect its output to the whoIP file
Send another DNS request to another terminal with dig
STOP TCPDUMP ctrl + c
grep file
Firstly, the problem is that I can’t put this sequence in the script, because tcpdump works until it sends a termination signal (here is a snag). If the script is looking to start tcpdump, then the following commands are not executed, because tcpdump works endlessly.
Tell me, is it possible to write this script, and in general, am I going the right way, which I doubt very much. It seems to me that there should be a simpler solution.