#!/bin/bash
# Author: Christophe Casalegno / Brain 0verride
# Contact: brain@christophe-casalegno.com
# sxnetstat
# Version 1.0
#
# Copyright (c) 2020 Christophe Casalegno
# 
# This program is free software: you can redistribute it and/or modify
#
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>
#
# The license is available on this server here: 
# https://www.christophe-casalegno.com/licences/gpl-3.0.txt

number_ip=$1
reverse_lookup=$2
ignore_list=("0.0.0.0" "1.1.1.1" "8.8.8.8" "9.9.9.9" "127.0.0.1")

if [ -z $number_ip ]
then
	number_ip=10
fi


function check_ignorelist()
{

	local ip=$1

	for ignored_ip in "${ignore_list[@]}"
	do
		if [ "$ip" == "$ignored_ip" ]
		then
			return 1
		fi
	done
	return 0

}

function get_ips()
{
netstat -tanpu |grep -v ':::' |grep ':[0-9]\+' |awk {'print $5'} |cut -d ':' -f1 |sort |uniq -c |sort -nk 1 |tail -n $number_ip
}

function filter_ips()
{

get_ips |while read count ip
do
	if check_ignorelist "$ip"
	then
		if [ "$reverse_lookup" == "1" ]
		then
			host_info=$(host "$ip" |awk '/domain name pointer/ {print $5}')
			if [ -z "$host_info" ]
			then
				host_info="N/A"
			fi
			echo "$count $ip $host_info"
		else
		echo "$count $ip"
		fi
	fi
done	
}


function get_ips()
{
	netstat -tanpu |grep -v ':::' |grep ':[0-9]\+' |awk {'print $5'} |cut -d ':' -f1 |sort |uniq -c |sort -nk 1 |tail -n $number_ip
}

function filter_ips() 
{
	get_ips | while read count ip 
	do
		[ -z "$ip" ] && continue  # skip si l'IP est vide

		if check_ignorelist "$ip" 
		then
			if [ "$reverse_lookup" == "1" ] 
			then
	                	host_info=$(host "$ip" 2>/dev/null | awk '/domain name pointer/ {print $5}')
		                [ -z "$host_info" ] && host_info="N/A"
		                echo "$count $ip $host_info"
	          	else
		                echo "$count $ip"
		
			fi

		fi

	done	
}

filter_ips
