如何檢查變量是否包含在python中的DNS名稱或IP地址?python:檢查IP或DNS
3
A
回答
6
您可以使用Python的re模塊來檢查變量的內容是否爲IP地址。 IP地址爲
舉例:
import re
my_ip = "192.168.1.1"
is_valid = re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", my_ip)
if is_valid:
print "%s is a valid ip address" % my_ip
例如,對於主機名:
import re
my_hostname = "testhostname"
is_valid = re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname)
if is_valid:
print "%s is a valid hostname" % my_hostname
+1
IPv6如何? – Sardathrion 2012-07-20 09:22:04
+1
http://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python/4017219#4017219 – 2012-07-20 09:54:44
1
我想看看這個SO問題的答案:
Regular expression to match DNS hostname or IP Address?
主要的一點是把這兩個正則表達式和它們放在一起來獲得desi紅色的結果。
0
print 'ip' if s.split('.')[-1].isdigit() else 'domain name'
這並不驗證任何一個是否格式良好。
8
這將工作。
import socket
host = "localhost"
if socket.gethostbyname(host) == host:
print "It's an IP"
else:
print "It's a host name"
相關問題
- 1. 檢查ip和DNS名稱
- 2. Python IP檢查
- 3. DNS IP檢查cpanel提醒/通知
- 4. DNS動態IP
- 5. DNS查詢:從DNS /主機名獲取IP地址
- 6. 檢查IP地址
- 7. DNS服務器IP地址
- 8. DevOps,DNS和公共IP
- 9. 寫DNS而不是IP?
- 10. 瞭解DNS和IP地址
- 11. 查詢DNS服務記錄查找主機名和TCP/IP
- 12. 如何檢查IP地址或代理工作或沒有
- 13. 如何使用pod IP上的kube-dns啓用反向DNS查找?
- 14. 檢查真實IP IP地址的NodeJS
- 15. 使用perl和Net :: DNS進行DNS檢查
- 16. 如何使用C++在Windows上檢索我的ISP的DNS IP?
- 17. 使用DNS檢查域的可用性
- 18. 檢查在Android中禁用DNS緩存
- 19. web.config中的Azure DNS主機名或IP引用?
- 20. IP檢查再次蠻力
- 21. BASH IP地址檢查
- 22. 檢查IP是在LAN
- 23. 檢查IP是子網
- 24. 是http_x_forwarded_for安全檢查IP
- 25. 檢查IP陣列與Bash
- 26. Python - DNS查詢從SQL數據庫
- 27. 檢查unicode的值True或False Python
- 28. 從Bash或Python檢查郵件主題
- 29. 查找DNS服務器和網關的IP和MAC地址
- 30. VB6查找主機在IP,指定DNS服務器
可能重複http://stackoverflow.com/q/3462784/280730 – 2011-03-28 15:39:00
和http://stackoverflow.com/q/319279/280730 [正則表達式匹配的主機名或IP地址的 – 2011-03-28 15:39:50
可能重複? ](http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address) – 2011-03-28 15:42:38