homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  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
Receive curated news, vulnerabilities, & security awareness tips
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
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
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
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

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Recommended Training

  • SEC550: Cyber Deception - Attack Detection, Disruption and Active Defense
  • SEC673: Advanced Information Security Automation with Python
  • SEC660: Advanced Penetration Testing, Exploit Writing, and Ethical Hacking

Tags:
  • Penetration Testing and Red Teaming

Related Content

Blog
HackFest_Blog.png
Penetration Testing and Red Teaming
November 14, 2022
A Visual Summary of SANS Pen Test HackFest Summit 2022
On November 14-15, attendees joined us in Arlington, VA or tuned in Live Online for the SANS Pen Test HackFest Summit! We invited Ashton Rodenhiser of Mind's Eye Creative to create graphic recordings of our Summit presentations. If you missed a talk or are looking to view the Summit through a...
370x370-person-placeholder.png
Alison Kim
read more
Blog
SEC673_340x340.png
Penetration Testing and Red Teaming, Cyber Defense
September 28, 2022
New SANS Python Course | SEC673: Advanced Information Security Automation with Python
SEC673 Advanced Information Security Automation with Python teaches how to write Python code to be faster, more efficient, and easier to maintain.
370x370-person-placeholder.png
Emily Neuens
read more
Blog
powershell_option_340x340.jpg
Cyber Defense, Cybersecurity and IT Essentials, Cloud Security, Penetration Testing and Red Teaming
July 17, 2022
Month of PowerShell: Merging Two Files (Understanding ForEach)
A routine task (merging two files) leads us down the path of developing a better understanding of the ForEach command in PowerShell.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
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
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
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
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

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn