简体   繁体   中英

How to convert an IP address to a string in python

This is my code

import socket
ip=56.90.89.78
ip2=str(IP)
M=socket.gethostbyaddr(ip2)
print (m)

You have to save your ip adress as a string and not a float or integer because it has multiple decimals. Also you need to be consistent with your upper and lower cases. Your code should be:

import socket 
ip = "56.90.89.78"
M = socket.gethostbyaddr(ip)
print(M)

If you just want to "convert" a literal IP address into a string, then like juanpa mentioned, it's just a matter of quoting in single or double quotes:

ip = "56.90.89.78"

If on the other hand, you want to resolve the IP address to a name, then you could indeed use the socket.gethostbyaddr function:

import socket
ip = "56.90.89.78"
name = socket.gethostbyaddr(ip)
print(name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM