问题
Recently i was asked a question in an interview which i couldn't do. Anyone got a solution for this?
Grab all connected IP´s on the Linux machine
check every connected IP if TCP port 1706 is open
if its open > execute command. CURL ‘http:// some address ’
Else do nothing.
program will check this every 60 minits
Plattform Linux Ubuntu Server 12. X64 / x32
WAP in C++
Thanks!!
回答1:
Make a bash script.
LOGIC:
Use netstat -natp
(filter it through awk
/sed
to get the ports, then grep it) Then use a simple test to see if the result was empty. Run curl
if it was.
Put this in a cron job. Simple stuff, really.
EDIT:
netstat
is a utility which will show you all of the connections on your computer. netstat -natp
shows a list of the programs which have tcp sockets on your computer.
sed
and awk
are used for text formatting. You can use them to list a specific column.
grep
searches input to find a specified string.
bash allows for basic logic, and can be used to see if a string is empty.
cron
is a linux process which schedules commands to be run at certain times.
EDIT #2:
You COULD poll /proc/net/tcp
, but since netstat
does that and formats it nicely, why bother?
回答2:
In Linux, you look for files in /proc/net
and parse that.
For example, TCP connections are listed in /proc/net/tcp
head /proc/net/tcp
will show something like this
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:0007 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 38148735 1 0000000000000000 100 0 0 10 -1
1: 00000000:1F48 00000000:0000 0A 00000000:00000000 00:00000000 00000000 116 0 38923158 1 0000000000000000 100 0 0 10 -1
2: 00000000:0CEA 00000000:0000 0A 00000000:00000000 00:00000000 00000000 120 0 12364094 1 0000000000000000 100 0 0 10 -1
3: 0100007F:13AD 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 26454267 1 0000000000000000 100 0 0 10 -1
4: 0100007F:008F 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5570 1 0000000000000000 100 0 0 10 -1
5: 00000000:0050 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 27328173 1 0000000000000000 100 0 0 10 -1
6: 0100007F:1913 00000000:0000 0A 00000000:00000000 00:00000000 00000000 116 0 38923868 1 0000000000000000 100 0 0 10 -1
7: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 18983193 1 0000000000000000 100 0 0 10 -1
8: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 38681424 1 0000000000000000 100 0 0 10 -1
You can then split the lines, look for the open connections and act accordingly. Look at thesource of netstat
for more.
来源:https://stackoverflow.com/questions/14910700/get-all-connected-ip%c2%b4s-on-the-linux-machine