广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python利用标准库如何获取本地IP示例详解
  • 437
分享到

python利用标准库如何获取本地IP示例详解

示例详解标准 2022-06-04 19:06:54 437人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

标准库 python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML

标准库

python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML处理等额外的功能。

Python标准库的主要功能有:

1.文本处理,包含文本格式化、正则表达式匹配、文本差异计算与合并、Unicode支持,二进制数据处理等功能

2.文件处理,包含文件操作、创建临时文件、文件压缩与归档、操作配置文件等功能

3.操作系统功能,包含线程与进程支持、io复用、日期与时间处理、调用系统函数、日志(logging)等功能

4.网络通信,包含网络套接字,SSL加密通信、异步网络通信等功能

5.网络协议,支持Http,FTP,SMTP,POP,IMAP,NNTP,XMLrpc等多种网络协议,并提供了编写网络服务器框架

6.W3C格式支持,包含html,SGML,XML的处理。

7.其它功能,包括国际化支持、数学运算、HASH、Tkinter等

python利用标准库获取本地IP

这个最简单,但是也最不靠谱,依赖hosts文件,如果hosts文件没配置,一般容易获取到127.0.0.1


import Socket
socket.gethostbyname(socket.gethostname())

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()

import socket
alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"
 
 
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
 
 
print((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0])
 
 
 
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
 
 
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])

import os
import socket
 
if os.name != "nt":
 import fcntl
 import struct
 
 def get_interface_ip(ifname):
 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
  ifname[:15]))[20:24])
 
def get_lan_ip():
 ip = socket.gethostbyname(socket.gethostname())
 if ip.startswith("127.") and os.name != "nt":
 interfaces = [
 "eth0",
 "eth1",
 "eth2",
 "wlan0",
 "wlan1",
 "wifi0",
 "ath0",
 "ath1",
 "ppp0",
 ]
 for ifname in interfaces:
 try:
 ip = get_interface_ip(ifname)
 break
 except IOError:
 pass
 return ip

linux上根据网卡名获取ip


>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>>
>>> def get_ip(iface = 'eth0'):
... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, 'x00'*14)
... try:
... res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
... except:
... return None
... ip = struct.unpack('16sH2x4s8x', res)[2]
... return socket.inet_ntoa(ip)
...
>>> get_ip('eth0')
'10.80.40.234'
>>>

仅限windows


def getIPAddresses():
 from ctypes import Structure, windll, sizeof
 from ctypes import POINTER, byref
 from ctypes import c_ulong, c_uint, c_ubyte, c_char
 MAX_ADAPTER_DESCRIPTION_LENGTH = 128
 MAX_ADAPTER_NAME_LENGTH = 256
 MAX_ADAPTER_ADDRESS_LENGTH = 8
 class IP_ADDR_STRING(Structure):
 pass
 LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
 IP_ADDR_STRING._fields_ = [
 ("next", LP_IP_ADDR_STRING),
 ("ipAddress", c_char * 16),
 ("ipMask", c_char * 16),
 ("context", c_ulong)]
 class IP_ADAPTER_INFO (Structure):
 pass
 LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
 IP_ADAPTER_INFO._fields_ = [
 ("next", LP_IP_ADAPTER_INFO),
 ("comboIndex", c_ulong),
 ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
 ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
 ("addressLength", c_uint),
 ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
 ("index", c_ulong),
 ("type", c_uint),
 ("dhcpEnabled", c_uint),
 ("currentIpAddress", LP_IP_ADDR_STRING),
 ("ipAddressList", IP_ADDR_STRING),
 ("gatewayList", IP_ADDR_STRING),
 ("dhcpServer", IP_ADDR_STRING),
 ("haveWins", c_uint),
 ("primaryWinsServer", IP_ADDR_STRING),
 ("secondaryWinsServer", IP_ADDR_STRING),
 ("leaseObtained", c_ulong),
 ("leaseExpires", c_ulong)]
 GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
 GetAdaptersInfo.restype = c_ulong
 GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
 adapterList = (IP_ADAPTER_INFO * 10)()
 buflen = c_ulong(sizeof(adapterList))
 rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
 if rc == 0:
 for a in adapterList:
 adnode = a.ipAddressList
 while True:
 ipAddr = adNode.ipAddress
 if ipAddr:
  yield ipAddr
 adNode = adNode.next
 if not adNode:
  break

第三方库

https://GitHub.com/ftao/python-ifcfg (本地下载)


import ifcfg
import JSON
 
for name, interface in ifcfg.interfaces().items():
 # do something with interface
 print interface['device']
 print interface['inet']
 print interface['inet6']
 print interface['netmask']
 print interface['broadcast']
 
default = ifcfg.default_interface()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程网的支持。

--结束END--

本文标题: python利用标准库如何获取本地IP示例详解

本文链接: https://www.lsjlt.com/news/16274.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python利用标准库如何获取本地IP示例详解
    标准库 Python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML...
    99+
    2022-06-04
    示例 详解 标准
  • Python中如何使用自带socket库获取本机IP地址
    小编给大家分享一下Python中如何使用自带socket库获取本机IP地址,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!使用自带...
    99+
    2022-10-19
  • python使用标准库根据进程名如何获取进程的pid详解
    前言 标准库是Python的一个组成部分。这些标准库是Python为你准备好的利器,可以让编程事半功倍。特别是有时候需要获取进程的pid,但又无法使用第三方库的时候。下面话不多说了,来一起看看详细的介绍吧。...
    99+
    2022-06-04
    进程 详解 标准
  • Python中如何使用第三方netifaces库获取本机IP地址
    这篇文章主要介绍Python中如何使用第三方netifaces库获取本机IP地址,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!使用第三方netifaces库获取的是局域网IP。net...
    99+
    2022-10-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作