python 获取本机ip和mac
时间: 2023-08-22 16:10:01 浏览: 176
你可以使用 Python 的 socket 和 uuid 模块来获取本机的 IP 地址和 MAC 地址。
获取 IP 地址的代码示例:
```python
import socket
# 获取本机的 IP 地址
ip_address = socket.gethostbyname(socket.gethostname())
print(ip_address)
```
获取 MAC 地址的代码示例:
```python
import uuid
# 获取本机的 MAC 地址
mac_address = ':'.join(format(s, '02x') for s in uuid.getnode().to_bytes(6, 'big'))
print(mac_address)
```
需要注意的是,获取 MAC 地址的代码可能在 Windows 系统上无法正常运行。在 Linux 和 macOS 系统上则可以正常运行。
相关问题
python 获取linux 网卡IP地址和mac地址
在Python中,你可以使用内置模块如`ipifaces`、`netifaces`或者第三方模块`psutil`来获取Linux系统的网卡IP地址和MAC地址。这里以`netifaces`为例,这是一个广泛用于网络配置信息查询的库:
```python
import netifaces
def get_ip_address_and_mac(interface_name='eth0'):
try:
# 获取指定网卡的信息
ifi = netifaces.ifaddresses(interface_name)
# 对于IPv4地址
ip_address =ifi[netifaces.AF_INET][0]['addr']
# 对于MAC地址(通常在IFADDRS层)
mac_address = ifi[netifaces.AF_LINK][0]['addr']
return ip_address, mac_address
except Exception as e:
print(f"Failed to get IP and MAC address for {interface_name}: {e}")
return None, None
# 使用示例
ip, mac = get_ip_address_and_mac()
if ip and mac:
print(f"Interface {interface_name} has IP address: {ip}, MAC address: {mac}")
else:
print("No valid network interface found.")
```
python收集linux IP地址和mac地址
你可以使用 Python 中的 `socket` 和 `subprocess` 模块来收集 Linux 系统上的 IP 地址和 MAC 地址。以下是一个示例代码:
```python
import socket
import subprocess
# 获取主机名
host_name = socket.gethostname()
# 获取 IP 地址
ip_address = socket.gethostbyname(host_name)
# 获取所有网络接口信息
ifconfig_result = subprocess.run(['ifconfig'], stdout=subprocess.PIPE).stdout.decode('utf-8')
# 解析出每个网络接口的 IP 地址和 MAC 地址
interface_info = {}
for line in ifconfig_result.split('\n'):
if line.startswith(' '):
# 处理多行输出的情况
interface_info[interface_name]['output'].append(line.strip())
continue
if ':' in line:
# 解析出网络接口名称和 MAC 地址
parts = line.split()
interface_name = parts[0].strip(':')
mac_address = parts[1]
interface_info[interface_name] = {'mac_address': mac_address, 'output': [line.strip()]}
else:
interface_name = None
# 输出结果
print('Hostname:', host_name)
print('IP address:', ip_address)
for interface_name, info in interface_info.items():
print('Interface:', interface_name)
print(' MAC address:', info['mac_address'])
print(' Output:')
for line in info['output']:
print(' ', line)
```
这段代码可以输出主机名、主机的默认 IP 地址,以及每个网络接口的 IP 地址和 MAC 地址。注意,如果一个网络接口有多个 IP 地址,这段代码只会输出其中的一个 IP 地址。如果需要获取所有 IP 地址,需要对代码进行相应的修改。
阅读全文
相关推荐















