How to Find Details about Your Network Interfaces and Ports in Python



Python


In this article, we show how to find details about your network interfaces and ports in Python.

netstat or Network Statistics is a useful command-line newtwork utility used to display various statistics such as network connnections, network interfaces, network protocol statistics like active sockets for each protocol, and routing table details.

For a cybersecurity professional, netstat is one of the tools used frequently to find out about the system's security posture by looking at the open ports and understanding the services running on those ports.

While netstat may not be available by default for all operating systems, we can use Python to achieve the same functionality.

psutils is probably the best Python module to achieve various functions related to the network.

In this article, we show how to implement netstat functionaliyt in Python to check details about ports and services.

We use net_connection from psutils to check for all the netstat functionality.

The first thing we must do to get this functionality in Python is to install the psutil module, which we do with the following line shown below.

pip install psutil







So let's now go over the code.

First, we have to import net_connections from psutil

We create a class, NetStats

We then create a function, print_net_connections(), which prints out the network connections present on the user's system.

We first print out the system's TCP connections and then the UDP connections.

We then have our main function, which executes the code.

A simpler version of this code is shown below.





The code above produces the following output shown below.





So this exposes you to all types of ports within the TCP connections and the UDP connections.

You can see their port numbers and their pid numbers.

And this is a way that you can find details about your network interfaces and ports using nestat with Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...