简体   繁体   中英

Extract IPv4 address from ifconfig output using regex

Hey i need a little help trying to get the gateway IP from this using the 're' import in python. (I'm trying to get the 'broadcast' bit in eth0) can anyone help me with the regex expression. Many thanks.

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
    inet6 fe80::a00:27ff:feb4:9403  prefixlen 64  scopeid 0x20<link>
    ether 08:00:27:b4:94:03  txqueuelen 1000  (Ethernet)
    RX packets 81508  bytes 94760761 (90.3 MiB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 80331  bytes 134321242 (128.0 MiB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Not sure why you would use regex against shell output of ifconfig which is highly susceptible to changes between distributions of *nix, bsd, etc. etc.

here is a pure python solution:

>>> import netifaces as ni
>>> ni.ifaddresses('en0')[2][0]['broadcast']
u'192.168.0.255'

Well, here it is both ways. Take your pick.

import re

s = """
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
    inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
    inet6 fe80::a00:27ff:feb4:9403  prefixlen 64  scopeid 0x20<link>
    ether 08:00:27:b4:94:03  txqueuelen 1000  (Ethernet)
    RX packets 81508  bytes 94760761 (90.3 MiB)
    RX errors 0  dropped 0  overruns 0  frame 0
    TX packets 80331  bytes 134321242 (128.0 MiB)
    TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
"""

# Bit values - see /usr/include/linux/if.h
IFF_UP        = 1<<0
IFF_BROADCAST = 1<<1
IFF_RUNNING   = 1<<6
IFF_MULTICAST = 1<<12

# Method 1 - Collect the flags integer value.
rf = re.compile(r'flags=(?P<flags>\d+)')
m = rf.search(s)
if m:
    flags = int(m.group('flags'))
    print('Your flags {0:d} (decimal) is {0:X}'.format(flags, flags))

    # Note the bitwise and operator here:
    if flags & IFF_BROADCAST:
        print('BROADCAST bit is ON')

# Method 2 - Collect the flag names.
rn = re.compile(r'flags=\d+<(?P<names>.+)>')
m = rn.search(s)
if m:
    names = m.group('names').split(',')
    print('Your names are ', names)
    if 'BROADCAST' in names:
        print('BROADCAST bit is ON')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM