3

I'm trying to match ip address using ip address that i input myself and ip address that grep using os on python, but when i run my code, the code say not match

app = Tk()
app.title('IP Address')
app.geometry('250x150+200+200')
b = StringVar()

ip = os.popen("ip -4 addr show wlan0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'").read()
#this will insert wlan0 ip address to variable ip
print(ip)

def com():
        c = b.get()
        if c == ip:
                labl3 = Label(text='Match').pack()
                app.destroy()
        else:
                labl3 = Label(text='Not Match').pack()

labl1 = Label(text='Input Ip address',font=30).pack()

text = Entry(textvariable=b).pack()

button1 = Button(text='Press to print', command= com).pack()

app.mainloop()

how i fix this?

4 Answers4

2

c == ip will only evaluate true if the two strings are exactly equal, character for character.

It is likely that this is not evaluating to true because the ip has some trailing white-space characters (in fact, I just ran the command, and it does indeed include a trailing new-line character).

You should therefore compare them like this instead: c.strip() == ip.strip()

the .strip() method removes all trailing and leading whitespace in a given string. The above command is therefore comparing the trailing/leading whitespace removed versions of the strings.


Tip: if you want to debug something like this in future, check len(c) and len(ip) and see if they are the same length.

Pixelchai
  • 488
  • 4
  • 13
2

If you're using python3, there is an ipaddress module. One would use it as follows:

if ipaddress.ip_address(str(lab1)): # valid ip
    pass # or whatever
else:
    raise Exception('Invalid ip address')

If you're using python2, there's a backport. Hope this helps.

hd1
  • 33,938
  • 5
  • 80
  • 91
0

You can do that by modifying your regex

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

its because . is a wildcard that stands for "every character" .

0

A couple of questions to get started.

I'm assuming you are running this on a *nix machine because of the use of the ip command, unless you have installed iproute2mac for mac or on linux for windows. Could you tell us what platform you are running on? Also, can you tell me the output of the command ip -4 addr show (please omit any details you don't want to share online). Besides platform related things, it could be an issue with string trimming or character escaping. If you could provide a print debug of the inputs that would be super helpful as well.

Thanks!

Hunterrex
  • 590
  • 6
  • 9
  • im using raspberry pi and found that command on (https://stackoverflow.com/questions/8529181/which-terminal-command-to-get-just-ip-address-and-nothing-else) – Dwijaya Kongky Salim Jan 08 '19 at 22:20