1

I need to do this as part of validation, I have a solution for IPv4. But since IPv6 can have many formats, I am not able to find the exact solution. Any suggestions?

char
  • 2,063
  • 3
  • 15
  • 26
user1581221
  • 21
  • 1
  • 2
  • 4
    Welcome to Stack Overflow! We encourage you to [research your questions](http://stackoverflow.com/questions/how-to-ask). If you've [tried something already](http://whathaveyoutried.com/), please add it to the question - if not, research and attempt your question first, and then come back. –  Aug 07 '12 at 08:38

3 Answers3

2

There many way to solve you problem. You can start from the solution for similar task:

The idea is to use the socket module from Python:

socket.inet_pton(socket.AF_INET6, address)
Community
  • 1
  • 1
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • So now with inet_pton i get the binary format of the IP address , But how can i check if that was in the network range. – user1581221 Aug 07 '12 at 15:37
2

Since Python 3.3, you can use

import ipaddress
ipaddress.ip_address(ip) in ipaddress.IPv6Network(network)

For example,

import ipaddress
ip = "2001:db8:85a3::8a2e:370:7334"
network = "2001:db8:85a3::/64"
test = ipaddress.ip_address(ip) in ipaddress.IPv6Network(network)
print(test)   # True

There is also a backport for Python 2.6+.

EDIT: You can use the following function as well which supports both IPv4 and IPv6

ipaddress.ip_network(addr)
rkachach
  • 16,517
  • 6
  • 42
  • 66
Peter Thomassen
  • 1,671
  • 1
  • 16
  • 28
0

Check out IPy. It is really useful when dealing with IP addresses and subnets in Python.

Sander Steffann
  • 9,509
  • 35
  • 40