Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

sockets - How can i find the ips in network in python

How can i find the TCP ips in network with the range(i.e 132.32.0.3 to 132.32.0.44) through python programming and also want to know the which ips are alive and which are dead. please send me.. thanks for the repliers...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Part 1 - "Finding IPs"

Your example range, 132.32.0.3 to 132.32.0.44 doesn't match any subnet, which is curious.

Typically applications for checking whether hosts are up and down are normally scoped within a subnet, e.g. 192.168.0.0/28 (host addresses: 192.168.0.1 to 192.168.0.14).

If you wanted to calculate the addresses within a subnet, I'd suggest you use ipaddr. E.g.:

>>> from ipaddr import IPv4Address, IPNetwork
>>> for a in IPNetwork('192.168.0.0/28').iterhosts():
...   print a
...
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14

However, if you're sure that you want an arbitrary range. You can convert an IPv4 address to an integer, increment and convert back to dotted IP. E.g.:

def aton(a):
  """
  Change dotted ip address to integer
  e.g. '192.168.0.1' -> 3232235521L
  """
  return reduce(lambda x,y: (x<<8) + y, [ int(x) for x in a.split('.') ])

def ntoa(n):
  """
  Change an integer to a dotted ip address.
  e.g. 3232235522L -> '192.168.0.2'
  """
  return "%d.%d.%d.%d" % (n >> 24,(n & 0xffffff) >> 16,(n & 0xffff) >> 8,(n & 0xff))

def arbitraryRange(a1,a2):
  """
  Generate all IP addresses between two addresses inclusively
  """
  n1, n2 = aton(a1), aton(a2)
  assert n1 < n2
  i = n1
  while i <= n2:
    yield ntoa(i)
    i += 1

Providing:

>>> for a in arbitraryRange('192.168.0.10','192.168.0.20'):
...   print a
...
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
192.168.0.16
192.168.0.17
192.168.0.18
192.168.0.19
192.168.0.20

Part 2 - "Alive or Dead"

The question of "alive" or "dead" is complex and entirely dependent on what you mean by those terms. To provide context and contrast, here's a list of testable qualities with regard to an IP address / host:

  • Responds to ARP request?
  • Responds to ICMP echo request?
  • Responds to TCP SYN?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...