Python 获取用户 IP 地址并保存到文件
以下是一个简单的 Python+HTML 代码,可以获取用户的 IP 地址并将其保存在'1.txt' 文件中:
Python 代码:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
ip = request.remote_addr
with open('1.txt', 'w') as f:
f.write(ip)
return 'Your IP address is: {}'.format(ip)
if __name__ == '__main__':
app.run()
HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>获取 IP 地址</title>
</head>
<body>
<h1>欢迎访问 IP 地址页面</h1>
<p>您的 IP 地址是:<span id='ip'></span></p>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.ipify.org', true);
xhr.onload = function () {
document.getElementById('ip').textContent = xhr.responseText;
};
xhr.send();
</script>
</body>
</html>
运行上述 Python 代码后,在浏览器中访问 http://localhost:5000/,将会显示用户的 IP 地址,并将其保存在'1.txt' 文件中。请注意,该代码需要安装 Flask 库才能运行。
原文地址: https://www.cveoy.top/t/topic/n9DL 著作权归作者所有。请勿转载和采集!