Python Forum
regex help to get the local ip address
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regex help to get the local ip address
#1
hey all... need a help in regex ..

im trying to get the local ip address form a windows system by running this code : ( i dont want to use python socket )
import os
import re

q = os.popen("""ipconfig | findstr /R /C:"IPv4 Address""").read()
print q 
dev = re.findall('[0-9]+' , q)
print dev
the result is : ['4', '192', '168', '74', '163']
the cmd result is : IPv4 Address. . . . . . . . . . . : 192.168.74.163

i need to get just this result : 192.168.74.163
how i can do it by regex ??

thanks in advance
Reply
#2
solved :

from os import popen
from re import findall

q = popen("""ipconfig | findstr /R /C:"IPv4 Address""").read()
print q 
dev = findall( r'[0-9]+(?:\.[0-9]+){3}' , q)
print dev[0]
Reply
#3
import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
Reply
#4
(Sep-26-2018, 12:15 PM)Axel_Erfurt Wrote:
import socket
print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
thank u very much dear
Reply
#5
>>> import re
>>> response = 'IPv4 Address. . . . . . . . . . . : 192.168.74.163 '
>>> match = re.search(r'((\d+\.?){4})', response)
>>> match.groups()
('192.168.74.163', '163')
But what happens if it's ipv6?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020