0

Yesterday I was asked a question in an interview to implement getIPAdrress() which could return the IP address of a system irrelevant of OS its running.

I tried to write it using os, subprocess module.where I first check for the os name and based on that I fire a command(ipconfig\ifconfig) using subprocess and then find and return the IP address from there.

I know this approach is not good as was told. I was further asked to some design pattern of my choice to do the same thing, basically which could run no matter what the os is, as if now my function would only run in windows and linux alike os.

with this post I want to learn if there is a better way of doing it.

Thanks, Learning Ninja

LearningNinja
  • 437
  • 1
  • 8
  • 23
  • 1
    Possible solutions, and some other comments: http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib To me that has nothing to do with design patterns... – Michał Zaborowski May 19 '16 at 13:59
  • Are you allowed to use 3rd party libraries? I implemented something like this using dns -- www.dnspython.org – Marcel Wilson May 19 '16 at 17:30

1 Answers1

0

Here is an interesting way to get your external facing IP cross platform.

import urllib

url = "http://checkip.amazonaws.com/"
response = urllib.urlopen(url).read().rstrip()
print response
Copy and Paste
  • 496
  • 6
  • 16
  • This way would need an internet connect. – LearningNinja May 19 '16 at 14:08
  • @LearningNinja if you are looking for your external IP, one would imply that you could reach the above address. If there are additional restrictions/requirements please include them in your question. In addition you never mentioned if we were attempting to obtain your private or public ip. – Copy and Paste May 19 '16 at 14:14