0

I'm trying to figure out how can I scan a class C ip range; For example a user provide by cmd line to my script : python script.py 192.168.0.0/24 (OR 192.168.0.1-255)

Let's figure my script does only a tcp connect action:

import socket, sys

host = sys.argv[1],65535

s = socket(AF_INET, SOCK_STREAM)

s.connect(host)

s.send("helloworld")

Do i really need to do a "for x in ip range" ?!? Or a build in module can do that ?

Thanks !

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
nabs2
  • 17
  • 1
  • 4
  • 1
    BTW: The term "Class C network" is deprecated since 1993 (RFC 1518 / 1519), because it means more than only "a net with 255 adresses". The /24 term you're also using is the right one. – IanH Aug 16 '10 at 09:38

4 Answers4

3

It doesn't take too much code it you want to do it in pure python

import socket, struct

def atod(a): # ascii_to_decimal
    return struct.unpack("!L",socket.inet_aton(a))[0]

def dtoa(d): # decimal_to_ascii
    return socket.inet_ntoa(struct.pack("!L", d))

net,_,mask = sys.argv[1].partition('/')
mask = int(mask)
net = atod(net)

for host in (dtoa(net+n) for n in range(0, 1<<32-mask)):
    print host
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

ipaddr-py is a really handy module for handling IP addresses and subnets.

>>> from ipaddr import IPv4Network
>>> net = IPv4Network('192.168.0.0/24')
>>> for host in net.iterhosts():
...     print repr(host)
...
IPv4Address('192.168.0.1')
IPv4Address('192.168.0.2')
IPv4Address('192.168.0.3')
IPv4Address('192.168.0.4')
..... and the rest
MattH
  • 37,273
  • 11
  • 82
  • 84
1

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux). This is the link for scanip (Ip and Mac scanner) written in python. https://pypi.python.org/pypi/scanip/1.0

You can also download it using pip install scanip on linux and to use it , create a test file in python and use it like this-

import scanip.scanip

scanip.scanip.start_scan()

and run this program . All the ip and their corresponding mac addresses in the LAN will be shown in the terminal.

vivkv
  • 931
  • 2
  • 14
  • 29
0

Have a look at List of IP addresses/hostnames from local network in Python.

There's no built-in way to do this; you can either use an external module or call some other program from Python.

Community
  • 1
  • 1
Katriel
  • 120,462
  • 19
  • 136
  • 170