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
2.2k 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 Reply

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.


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

...