在Python中,更改本地IP地址可以通过以下几种方法实现:
方法一:使用`socket`模块
```python
import socket
获取当前主机名和IP地址
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
print("当前 IP 地址:", ips)
修改主机名和IP地址
new_hostname = "newhostname"
new_ip_address = "192.168.1.100"
socket.sethostname(new_hostname)
socket.gethostbyname_ex(new_hostname)
修改网络接口的IP地址
socket.ifconfig("lo", [ "inet", new_ip_address, "netmask", "255.255.255.0" ])
再次获取新的IP地址
_, _, ips = socket.gethostbyname_ex(new_hostname)
print("新的 IP 地址:", ips)
方法二:使用`netifaces`库
```python
import netifaces
获取当前主机的IP地址
interfaces = netifaces.interfaces()
for interface in interfaces:
addresses = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addresses:
ip_address = addresses[netifaces.AF_INET]['addr']
print("当前 IP 地址:", ip_address)
修改指定网卡的IP地址
new_ip_address = "192.168.1.100"
netifaces.ifconfig(interface, new_ip_address)
再次获取新的IP地址
interfaces = netifaces.interfaces()
for interface in interfaces:
addresses = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addresses:
ip_address = addresses[netifaces.AF_INET]['addr']
print("新的 IP 地址:", ip_address)
方法三:使用`wmi`库(仅限Windows)
```python
import wmi
获取本地有网卡信息
wmiService = wmi.WMI()
colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
随机修改指定IP段的本机IP
def getAdapter():
for obj in colNicConfigs:
ip = re.findall("10.\d+\.\d+\.\d+", obj.IPAddress)
if len(ip) > 0:
return True
return False
def runSet():
adapter = colNicConfigs[getAdapter()]
这里需要根据具体情况修改适配器信息
运行设置
runSet()
方法四:修改Windows注册表(仅限Windows)
```python
import winreg
打开注册表项
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters")
遍历网络适配器,找到需要修改的那个
for i in range(0, winreg.QueryInfoKey(key)):
name = winreg.EnumKey(key, i)
这里需要根据具体情况修改适配器信息
修改该适配器的IP地址和子网掩码
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, "10.0.0.2")
winreg.SetValueEx(key, name, 1, winreg.REG_SZ, "255.255.255.0")
winreg.SetValueEx(key, name, 2, winreg.REG_SZ, "10.0.0.1")
关闭注册表
winreg.CloseKey(key)