Python擷取本機所有網卡ip,掩碼和廣播位址

來源:互聯網
上載者:User

標籤:python   ip地址   廣播位址   子網路遮罩   網卡   

搜了一天,竟然沒找到一段合適的代碼來擷取機器中所有網卡的ip,掩碼和廣播位址,大部分都是用socket,但是socket通常返回的要不就是內網地址,要不就是公網地址,不能夠找到所有地址,真的太憂桑了,決定自己通過ifconfig或ipconfig的返回資訊,一步步地過濾了。這次的代碼主要用到了Regex和subprocess模組,而且為了相容所有平台(win,linux和mac),也用到了platform來判斷系統類別型,不說太多,代碼如下:
import subprocessimport reimport platformdef find_all_ip(platform):    ipstr = ‘([0-9]{1,3}\.){3}[0-9]{1,3}‘    if platform == "Darwin" or platform == "Linux":        ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)        output = ipconfig_process.stdout.read()        ip_pattern = re.compile(‘(inet %s)‘ % ipstr)        if platform == "Linux":            ip_pattern = re.compile(‘(inet addr:%s)‘ % ipstr)        pattern = re.compile(ipstr)        iplist = []        for ipaddr in re.finditer(ip_pattern, str(output)):            ip = pattern.search(ipaddr.group())            if ip.group() != "127.0.0.1":                iplist.append(ip.group())        return iplist    elif platform == "Windows":        ipconfig_process = subprocess.Popen("ipconfig", stdout=subprocess.PIPE)        output = ipconfig_process.stdout.read()        ip_pattern = re.compile("IPv4 Address(\. )*: %s" % ipstr)        pattern = re.compile(ipstr)        iplist = []        for ipaddr in re.finditer(ip_pattern, str(output)):            ip = pattern.search(ipaddr.group())            if ip.group() != "127.0.0.1":                iplist.append(ip.group())        return iplistdef find_all_mask(platform):    ipstr = ‘([0-9]{1,3}\.){3}[0-9]{1,3}‘    maskstr = ‘0x([0-9a-f]{8})‘    if platform == "Darwin" or platform == "Linux":        ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)        output = ipconfig_process.stdout.read()        mask_pattern = re.compile(‘(netmask %s)‘ % maskstr)        pattern = re.compile(maskstr)        if platform == "Linux":            mask_pattern = re.compile(r‘Mask:%s‘ % ipstr)            pattern = re.compile(ipstr)        masklist = []        for maskaddr in mask_pattern.finditer(str(output)):            mask = pattern.search(maskaddr.group())            if mask.group() != ‘0xff000000‘ and mask.group() != ‘255.0.0.0‘:                masklist.append(mask.group())        return masklist    elif platform == "Windows":        ipconfig_process = subprocess.Popen("ipconfig", stdout=subprocess.PIPE)        output = ipconfig_process.stdout.read()        mask_pattern = re.compile(r"Subnet Mask (\. )*: %s" % ipstr)        pattern = re.compile(ipstr)        masklist = []        for maskaddr in mask_pattern.finditer(str(output)):            mask = pattern.search(maskaddr.group())            if mask.group() != ‘255.0.0.0‘:                masklist.append(mask.group())        return masklistdef get_broad_addr(ipstr, maskstr):    iptokens = map(int, ipstr.split("."))    masktokens = map(int, maskstr.split("."))    broadlist = []    for i in range(len(iptokens)):        ip = iptokens[i]        mask = masktokens[i]        broad = ip & mask | (~mask & 255)        broadlist.append(broad)    return ‘.‘.join(map(str, broadlist))def find_all_broad(platform):    ipstr = ‘([0-9]{1,3}\.){3}[0-9]{1,3}‘    if platform == "Darwin" or platform == "Linux":        ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)        output = (ipconfig_process.stdout.read())        broad_pattern = re.compile(‘(broadcast %s)‘ % ipstr)        if platform == "Linux":            broad_pattern = re.compile(r‘Bcast:%s‘ % ipstr)        pattern = re.compile(ipstr)        broadlist = []        for broadaddr in broad_pattern.finditer(str(output)):            broad = pattern.search(broadaddr.group())            broadlist.append(broad.group())        return broadlist    elif platform == "Windows":        iplist = find_all_ip(platform)        masklist = find_all_mask(platform)        broadlist = []        for i in range(len(iplist)):            broadlist.append(get_broad_addr(iplist[i], masklist[i]))        return broadlistsystem = platform.system()print(find_all_ip(system))print(find_all_mask(system))print(find_all_broad(system))

希望對大家有所協助:)

Python擷取本機所有網卡ip,掩碼和廣播位址

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.