Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

using inet_ntoa function in Python

I've recently started to program in python and I'm having some trouble understanding how inet_nota and inet_aton work in Python. Coming from php/mysql I've always stored ip addresses in the database as long variables. Also the inet_ntoa method in mysql receives a long variable as parameter and returns the dotted format of an IP, so I assumed the Python version works in a similar manner. However, it seems Python's inet_ntoa needs a 32-bit packed binary format. So, having the IP address stored as 167772160 value, how can I convert it to a 32-bit packed binary value (like x7fx00x00x01) which is needed by inet_ntoa method?

Thanks a lot

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

In Python 3.3+ (or with this backport for 2.6 and 2.7), you can simply use ipaddress:

import ipaddress
addr = str(ipaddress.ip_address(167772160))
assert addr == '10.0.0.0'

Alternatively, you can manually pack the value

import socket,struct
packed_value = struct.pack('!I', 167772160)
addr = socket.inet_ntoa(packed_value)
assert addr == '10.0.0.0'

You might also be interested in inet_pton.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...