How can i find the ips in network in python
How can i find the TCP ips in network with the ra开发者_JAVA百科nge(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...
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?
精彩评论