如何在python中为接口分配IP地址? [英] How to assign IP address to interface in python?

查看:329
本文介绍了如何在python中为接口分配IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有python脚本,可为我的无线和有线接口设置IP4地址.到目前为止,我使用subprocess命令,如:

I have python script that set the IP4 address for my wireless and wired interfaces. So far, I use subprocess command like :

subprocess.call(["ip addr add local 192.168.1.2/24 broadcast 192.168.1.255 dev wlan0"])

如何使用python库设置接口的IP4地址? 以及是否有任何方法可以使用python库获取已经存在的IP配置?

How can I set the IP4 address of an interface using python libraries? and if there is any way to get an already existing IP configurations using python libraries ?

推荐答案

通过较早的ioctl界面设置地址:

Set an address via the older ioctl interface:

import socket, struct, fcntl

SIOCSIFADDR = 0x8916
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


def setIpAddr(iface, ip):
    bin_ip = socket.inet_aton(ip)
    ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00' * 2, bin_ip, '\x00' * 8)
    fcntl.ioctl(sock, SIOCSIFADDR, ifreq)


setIpAddr('em1', '192.168.0.1')

(通过SIOCSIFNETMASK = 0x891C设置网络掩码)

可以通过相同的方式检索IP地址:查找使用Python的stdlib的本地IP地址

Ip addresses can be retrieved in the same way: Finding local IP addresses using Python's stdlib

我相信您想在ioctl

这篇关于如何在python中为接口分配IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆