在Windows上使用Python获取本地IP地址

作者:佚名 上传时间:2023-05-30 运行软件:Jupyter Notebook 软件版本:Python 3.6.5 版权申诉

本示例代码使用Python和Windows API获取本地IP地址,并将其打印出来。在使用Windows API时,需要引入ctypes库来调用Windows系统的API函数。

import socket
import ctypes

def get_local_ip_address():
    hostname = socket.gethostname()
    # 使用Windows API获取网络适配器信息
    mod = ctypes.windll
    adapter_buf = ctypes.create_string_buffer(20000)
    mod.iphlpapi.GetAdaptersAddresses(0, 0, None, adapter_buf, ctypes.byref(ctypes.c_ulong(len(adapter_buf))))
    # 解析网络适配器信息获取IP地址
    addresses = ctypes.cast(adapter_buf, ctypes.POINTER(mod.iphlpapi.IP_ADAPTER_ADDRESSES))
    while addresses:
        if addresses.contents.Description.decode('utf-8') == 'Realtek PCIe GBE Family Controller': # 适配器名称
            address = socket.inet_ntoa(addresses.contents.FirstUnicastAddress.contents.Address.lpSockaddr.contents.sin_addr)
            print("本机IP地址为:", address)
            break
        addresses = addresses.contents.Next

get_local_ip_address()

免责申明:文章和图片全部来源于公开网络,如有侵权,请通知删除 server@dude6.com

用户评论
相关推荐
Windows使用Python获取本地IP地址
本示例代码使用Python和Windows API获取本地IP地址,并将其打印出来。在使用Windows API时,需要引入ctypes库来调用Windows系统的API函数。import sock
Python 3.6.5
Jupyter Notebook
2023-05-30 03:33
如何在Windows使用Python获取本地IP地址
这段示例代码演示如何使用Python在Windows上获取本地IP地址。它使用了Python内置库socket和gethostname()函数来实现。gethostname()函数返回主机名,而soc
Python 3.9.5
Python
2023-04-09 04:23
Go语言获取本地IP地址windows
网上搜了很多go语言查找本地可用ip4,基本就是这一套 func main(){ addrs, err := net.InterfaceAddrs() if err != nil{
PDF
29KB
2021-02-01 18:03
Go语言获取本地IP地址windows
网上搜了很多go语言查找本地可用ip4,基本就是这一套 func main(){ addrs, err := net.InterfaceAddrs() if err != nil{
PDF
29KB
2021-02-01 18:03
获取本地IP地址
调用函数,利用套接字进行获取,然后将Ip地址转换后输出。
CPP
0B
2019-01-15 01:05
使用C#实现在Windows获取本地IP地址
本示例代码展示了如何在Windows操作系统上使用C#语言来获取本机的IP地址。它使用NetworkInformation类的GetIsNetworkAvailable和GetNetworkInter
Visual Studio 2017
C# Console Application
2023-04-29 13:43
如何在Windows Mobile设备获取本地IP地址
本例介绍如何通过C#代码在Windows Mobile设备上获取本地IP地址。实现方式是通过查询设备中所有的网络接口并获取它们的IP地址。using System.Net.NetworkInform
Windows Mobile 6.5
Visual Studio 2008
2023-05-20 18:07
获取本地ip mac地址
C#简单编写的一个获取本地ip,mac地址的小程序,C#简单编写的一个获取本地ip,mac地址的小程序
7Z
0B
2019-05-13 05:18
获取本地IP地址BAT
Get local, IP address BAT
BAT
0B
2019-06-26 02:15
symbian获取本地IP地址
Symbian get local IP address
RAR
0B
2019-06-26 02:15