0

I'm trying to get my IP and create a variable to hold that.

ipAddr = "F"

def ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ipAddr = s.getsockname()[0]
    s.close()

ip()
print(ipAddr)
#Returns F

When I print ipAddr after I run ip() I'd like it to return my ip. I know the code in ip() works, when I print ipAddr in the def block it prints my ip

2 Answers2

1

You can't modify global variables in a function without using the global keyword, so add it in:

ipAddr = "F"

def ip():
    global ipAddr
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ipAddr = s.getsockname()[0]
    s.close()

ip()
print(ipAddr)

However, this is generally bad practice. Better to do this:

ipAddr = "F"

def ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ipAddr = s.getsockname()[0]
    s.close()
    return ipAddr

ipAddr = ip()
print(ipAddr)
iz_
  • 15,923
  • 3
  • 25
  • 40
  • 1
    What about the first one makes it bad practice? – Austin Palmer Jan 03 '19 at 01:39
  • It's just bad practice to use global variables in basically any language. See https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – iz_ Jan 03 '19 at 01:40
  • @AustinPalmer If this answered your question, be sure to mark it as accepted for future viewers. https://stackoverflow.com/help/someone-answers – iz_ Jan 03 '19 at 01:42
0

Use a return statement.

ipAddr = "F"

def ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ipAddr = s.getsockname()[0]
    s.close()
    return ipAddr

# You can assign the return value to any variable name:
# ipAddr here and ipAddr in the function are different variables
ipAddr = ip()
print(ipAddr)
kindall
  • 178,883
  • 35
  • 278
  • 309