79733569

Date: 2025-08-12 19:03:22
Score: 0.5
Natty:
Report link

To find ip of nic eth0:

import os
ip = os.popen('"ip -4 -br addr show eth0 | grep -E -o '([0-9]{1,3}\.){3}[0-9]{1,3}'"').read().strip()
print(ip)
#Or using variable to define network interface card
nic = "eth0"
ip = os.popen('"ip -4 -br addr show " + nic + " | grep -E -o '([0-9]{1,3}\.){3}[0-9]{1,3}'"').read().strip()
print(ip)

Instead of using external tools like awk one can use a regular expression.

  1. Extend regular expression (-E)

  2. Print only the matched parts (-o)

([0-9]{1,3}\.){3}[0-9]{1,3}'"') -> Breaks into two parts

  1. ([0-9]{1,3}\.){3}

    1. [0-9] -> Digits 0 to 9.

    2. {1,3} -> Minimum 1 digit, maximum 3 digits.

    3. \. Adds a '.', the '\' works as a escape character.

    4. = {3} Repeats three times.

  2. [0-9]{1,3} Same as part 1, no '.', no repeat.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: IlCostinio