本文目錄一覽:
- 1、python使用Flask框架獲取用戶IP地址的方法
- 2、如何用Python獲取本機ip
- 3、python怎麼獲取本機ip
- 4、Python獲取url中域名及從域名中提取ip的方法
- 5、python 怎麼獲取本機的外網ip
python使用Flask框架獲取用戶IP地址的方法
主要介紹了python使用Flask框架獲取用戶IP地址的方法,實例分析了Python使用Flask框架remote_addr獲取IP的`技巧,非常具有實用價值,需要的朋友可以參考下。
下面的代碼包含了html頁面和python代碼,非常詳細,如果你正使用Flask,也可以學習一下最基本的Flask使用方法。
python代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user’s IP
@app.route(‘/’)
def index():
ip = request.remote_addr
return render_template(‘index.html’, user_ip=ip)
if __name__ == ‘__main__’:
app.run(
host=”0.0.0.0″,
port=int(“80”)
)
html代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
!DOCTYPE html
html lang=”en”
head
link href=”bootstrap/3.0.0/css/bootstrap.min.css”
rel=”stylesheet”
/head
body
p class=”container”
p class=”header”
h3 class=”text-muted”How To Get The IP Address Of The User/h3
/p
hr/
p
You IP address is: strong{{user_ip}}/strong
p class=”header”
h3 class=”text-muted”Code to retrieve the IP/h3
/p
hr/
pre
from flask import Flask, render_template, request
# Initialize the Flask application
app = Flask(__name__)
# Default route, print user’s IP
@app.route(‘/’)
def index():
ip = request.remote_addr
return render_template(‘index.html’, user_ip=ip)
/pre
/p
/p
/body
/html
希望本文所述對大家的Python程序設計有所幫助。
如何用Python獲取本機ip
import socket
localIP = socket.gethostbyname(socket.gethostname())#得到本地ip
print “local ip:%s “%localIP
python怎麼獲取本機ip
import socket
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn’t even have to be reachable
s.connect((‘10.255.255.255’, 0))
IP = s.getsockname()[0]
except:
IP = ‘127.0.0.1’
finally:
s.close()
return IP
linux、windows均測試通過
Python獲取url中域名及從域名中提取ip的方法
這種方法為從urlparse模塊中通過urlparse方法提取url通過hostname屬性獲取當前url的域名。
此方法是通過urllib模塊中splittype方法先從url中獲取到proto協議及rest結果,然後通過splithost從rest中獲取到host及rest結果,此時host為域名。(rest被分割了兩次)如下圖:
此方法為從sokcet模塊中獲取到gethostbyname方法將域名傳遞進去就能解析出域名的ip。
此方法為通過nslookup獲取域名的ip。
以上從域名中提取ip會不準確,需要設置DNS伺服器,這樣解析域名就準確了。
python 怎麼獲取本機的外網ip
import socket
hostname = socket.gethostname()
print hostname
LuciferYang.local
ip = socket.gethostbyname(hostname)
print ip
10.101.8.171
ipList = socket.gethostbyname_ex(hostname)
print ipList
(‘luciferyang.local’, [], [‘10.101.8.171’])
理論上,不是伺服器的話不用有直接外網IP到機器,辦公室環境或者家庭環境都是區域網環境,外網IP都在路由器上面
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/307457.html