【发布时间】:2021-01-23 17:46:44
【问题描述】:
我还是 python (PYTHON 3.9.1) 的新手,我正在尝试制作一个可以获取 ip 地址然后对其进行哈希处理的程序。我定义了一个获取 ip 地址的函数,然后删除点并将其转换为十六进制(我只是希望它对 ip 地址的十六进制进行哈希处理)。然后我定义了一个使用 SHA256 散列的函数。但是现在当我想在第一个函数中使用定义十六进制 IP 地址的本地定义变量时,在第二个函数中对其进行哈希处理,我只是不知道该怎么做。由于十六进制 IP 地址不是全局定义的,我不能在另一个函数中使用它。我可以将散列函数的代码放入第一个函数中,我做到了,它可以工作,但我不喜欢它,它使我的代码混乱,我认为必须有另一种方法来做到这一点.
主要问题是:如何在另一个函数中使用一个函数的本地定义变量?
这是我的代码:
import hashlib as hb
import socket
def get_ip():
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname) #If I was to print it, it would give a propper IP address
dotless_ip = ip.replace(".","")
hexidecimal_ip = hex(int(dotless_ip))
def sha256(): #This is the hashing function that uses SHA256 algorythm for hashing.
SHA256_convert = bytearray(input("Enter text to convert to SHA256 hash: "), "utf8") #If I was to hash something with this function, I would need to input stuff myself.
hasher = hb.sha256()
hasher.update(SHA256_convert)
print(hasher.hexdigest()) #This function works too, and the problem is not in it.
如您所见,get_ip() 函数中有一个本地定义的变量 hexidecimal_ip。 我想在我的 sha256() 函数中使用这个本地定义的变量,所以我所做的是:
def sha256():
SHA256_convert = bytearray(hexidecimal_ip), "utf8") #changing user input to a variable.
hasher = hb.sha256()
hasher.update(SHA256_convert)
print(hasher.hexdigest())
但是当然没用,因为变量不是全局定义的,所以接下来我做的是:
def get_ip():
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
dotless_ip = ip.replace(".","")
hexidecimal_ip = hex(int(dotless_ip))
return hexidecimal_ip #added a return statement here, in hopes that it will make the variable accessible globaly ( I still don't understand how return works )
def sha256():
SHA256_convert = bytearray(hexidecimal_ip), "utf8") #changing user input to a variable.
hasher = hb.sha256()
hasher.update(SHA256_convert)
print(hasher.hexdigest())
但是这也不起作用,所以对我来说唯一剩下的方法就是将它全部放入我所做的一个函数中并且它可以工作:
def get_ip():
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
print("Your IP address is:",ip) #I added a few print statements to check if function works and it does
dotless_ip = ip.replace(".","")
hexidecimal_ip = hex(int(dotless_ip))
print("Your IP address in hexidecimals is: ", hexidecimal_ip)
ip_hasher = hb.sha256() #changed the variable name a little bit, but it doesn't really matter
ip_hasher.update(bytearray(hexidecimal_ip, "utf8"))
print("Your hashed IP address is: ",ip_hasher.hexdigest())
所以在对我的问题进行了长时间的介绍之后,我的问题仍然存在:如何在另一个函数中使用一个函数中的本地定义变量?
【问题讨论】:
-
有什么理由没有函数 sha256 接受参数?这样你就可以传递它 hexidecimal_ip。
标签: python hash local-variables