homepage
Open menu Go one level top
  • Train and Certify
    • Get Started in Cyber
    • Courses & Certifications
    • Training Roadmap
    • Search For Training
    • Online Training
    • OnDemand
    • Live Training
    • Summits
    • Cyber Ranges
    • College Degrees & Certificates
    • NICE Framework
    • DoDD 8140
    • Specials
  • Manage Your Team
    • Overview
    • Security Awareness Training
    • Voucher Program
    • Private Training
    • Workforce Development
    • Skill Assessments
    • Hiring Opportunities
  • Resources
    • Overview
    • Reading Room
    • Webcasts
    • Newsletters
    • Blog
    • Tip of The Day
    • Posters
    • Top 25 Programming Errors
    • The Critical Security Controls
    • Security Policy Project
    • Critical Vulnerability Recaps
    • Affiliate Directory
  • Focus Areas
    • Blue Team Operations
    • Cloud Security
    • Digital Forensics & Incident Response
    • Industrial Control Systems
    • Leadership
    • Offensive Operations
  • Get Involved
    • Overview
    • SANS Community
    • CyberTalent
    • Work Study
    • Instructor Development
    • Sponsorship Opportunities
    • COINS
  • About
    • About SANS
    • Why SANS?
    • Instructors
    • Cybersecurity Innovation Awards
    • Contact
    • Frequently Asked Questions
    • Customer Reviews
    • Press Room
  • Log In
  • Join
  • Contact Us
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  1. Home >
  2. Blog >
  3. Python Tasks: Counting IP Addresses
370x370_Joshua-Wright.jpg
Joshua Wright

Python Tasks: Counting IP Addresses

When scoping a penetration test, it's common that I'll receive a list of target IP addresses in use. Sometimes this is in the form of CIDR masks...

February 18, 2021

When scoping a penetration test, it's common that I'll receive a list of target IP addresses in use. Sometimes this is in the form of CIDR masks:

~ $ head -5 targetnetworks.txt
15.230.56.104/31
52.93.127.163/32
3.2.0.0/24
15.230.137.0/24
52.4.0.0/14
~ $ wc -l targetnetworks.txt
     576 targetnetworks.txt

In this article we'll look at some ways to count the number of IP addresses in a list of CIDR mask netblocks. You can download the targetnetworks.txt file if you want to follow along.

The easy way to count the number of IP addresses in this list is to use Nmap. First, I'll create an excerpt of the targetnetworks.txt file called shortlist.txt:

~ $ head -4 targetnetworks.txt > shortlist.txt
Using Nmap, we can disable name resolution (-n), and use the list scan (-sL) feature to list the hosts that Nmap will scan, reading the list of hosts from the specified input file (-iL). Sending the output to wc -l allows us to count the number of lines:

~ $ nmap -n -sL -iL shortlist.txt | head
Starting Nmap 7.91 ( https://nmap.org ) at 2021-02-18 09:10 EST
Nmap scan report for 15.230.56.104
Nmap scan report for 15.230.56.105
Nmap scan report for 52.93.127.163
Nmap scan report for 3.2.0.0
Nmap scan report for 3.2.0.1
Nmap scan report for 3.2.0.2
Nmap scan report for 3.2.0.3
Nmap scan report for 3.2.0.4
Nmap scan report for 3.2.0.5
~ $ nmap -n -sL -iL shortlist.txt | wc -l
     517

Nmap will include the opening Starting Nmap line, and an Nmap done line at the end, so we subtract two from the number of lines to get the number of IP addresses. This is probably the most common method to count the number of IP addresses in a list of CIDR masks, but it is less than ideal since it is very slow:

~ $ time (nmap -n -sL -iL targetnetworks.txt | wc -l)
 32723890

real    2m49.440s
user    2m32.900s
sys    1m16.203s

I wanted to find a faster way to do this, so I put together a quick Python script. With Python 3.3 and later we have the ipaddress module, which includes the IPv4Network module to expand a CIDR mask into a generator of IP addresses:

~ $ python
Python 3.9.1 (default, Feb  1 2021, 20:42:01)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ipaddress
>>> ipaddress.IPv4Network("192.168.1.0/29")
IPv4Network('192.168.1.0/29')
>>> [str(ip) for ip in ipaddress.IPv4Network("192.168.1.0/29")]
['192.168.1.0', '192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6', '192.168.1.7']

Using ipaddress.IPv4Network, I created a little program to read the file with network numbers and CIDR masks, convert the generator into a list, and tally the number of entries:

~ $ cat countips.py
#!/usr/bin/env python
import sys, ipaddress

def countips(netblock):
    iplist = [str(ip) for ip in ipaddress.IPv4Network(netblock.rstrip())]
    return len(iplist)

if (len(sys.argv) != 2):
    print(f"Usage: {sys.argv[0]} <file with CIDR masks>")
    sys.exit(0)

ipcount=0
with open(sys.argv[1]) as infile:
    for netblock in infile:
        ipcount += countips(netblock)
    print(ipcount)
~ $ python countips.py shortlist.txt
515

This works well, but it suffers from a similar fate as the Nmap example (it is slow):

~ $ time python countips.py targetnetworks.txt
32723888

real    1m7.475s
user    1m6.485s
sys    0m0.857s

The ipaddress module isn't the issue here; the problem is my terrible use of list comprehension when converting the generator into a list for the purposes of counting the entries (e.g., the [str(ip) for ip in ipaddress.IPv4Network(netblock.rstrip())] bit. Fortunately, there is a better way to do this.

Math!

We don't need to generate a list of IP addresses to get a count, we just need to calculate the host part of the CIDR mask, then expand it to identify the number of hosts that it represents.

When we have a CIDR mask of /24, we indicate that 24 bits are used for the network portion of the address, and 8 bits are used for the host portion of the address. To calculate the number of hosts, we subtract the mask value from 32, then use that as an exponent:

~ $ python
Python 3.9.1 (default, Feb  1 2021, 20:42:01)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> cidr_mask=24
>>> 2**(32-cidr_mask)
256
>>> cidr_mask=16
>>> 2**(32-cidr_mask)
65536

A revised countips.py script:

~ $ cat countips.py
#!/usr/bin/env python
import sys

def countips(netblock):
    cidr = int(netblock.split('/')[1])
    return 2**(32 - cidr)

if (len(sys.argv) != 2):
    print(f"Usage: {sys.argv[0]} <file with CIDR masks>")
    sys.exit(0)

ipcount=0
with open(sys.argv[1]) as infile:
    for netblock in infile:
        ipcount += countips(netblock)
    print(ipcount)
~ $ python countips.py shortlist.txt
515

This revised script performs much better:

~ $ time python countips.py targetnetworks.txt
32723888

real    0m0.046s
user    0m0.029s
sys    0m0.012s

A Soliloquy on Programming

I'm often asked if you need to know programming to be a good cyber security analyst. I believe the answer is no, but to be a great analyst, the answer is probably yes. This doesn't mean that you need to spend all day coding and be able to write your own RDBMS platform from scratch, but it does mean that sometimes you'll want to be able to modify or augment other code, or develop your own code to automate a task on your own. It takes time and practice, but I have found the ability to solve problems with code a worthwhile pursuit.

-Josh

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Join the SANS Community to receive the latest curated cybersecurity news, vulnerabilities, and mitigations, training opportunities, plus our webcast schedule.
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kingdom of Saudi Arabia
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia (Slovak Republic)
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

Recommended Training

  • SEC642: Advanced Web App Penetration Testing, Ethical Hacking, and Exploitation Techniques
  • SEC660: Advanced Penetration Testing, Exploit Writing, and Ethical Hacking
  • SEC573: Automating Information Security with Python

Tags:
  • Penetration Testing and Ethical Hacking

Related Content

Blog
Penetration Testing and Ethical Hacking
February 4, 2021
Stack Canaries – Gingerly Sidestepping the Cage
Stack canaries or security cookies are tell-tale values added to binaries during compilation to protect critical stack values like the Return Pointer against buffer overflow attacks. If an incorrect canary is detected during certain stages of the execution flow, such as right before a return (RET),...
370x370_Michiel-Lemmens.jpg
Michiel Lemmens
read more
Blog
SUMMIT_Free_SANS_2021_Summits_Teaser.jpg
Digital Forensics and Incident Response, Cyber Defense Essentials, Industrial Control Systems Security, Purple Team, Blue Team Operations, Penetration Testing and Ethical Hacking, Cloud Security, Security Management, Legal, and Audit
November 30, 2020
Good News: SANS Virtual Summits Will Be FREE for the Community in 2021
They’re virtual. They’re global. They’re free.
Emily Blades
read more
Blog
shutterstock_382594525.jpg
Penetration Testing and Ethical Hacking
October 13, 2020
Red Team Tactics: Hiding Windows Services
A little known feature of Windows allows attackers to hide persistent services from view, creating an opportunity to evade threat hunting detection.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters
  • The Critical Security Controls
  • Focus Areas
  • Blue Team Operations
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Join the SANS Community to receive the latest curated cybersecurity news, vulnerabilities, and mitigations, training opportunities, plus our webcast schedule.
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kingdom of Saudi Arabia
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia (Slovak Republic)
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe
  • © 2021 SANS™ Institute
  • Privacy Policy
  • Contact
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn