-1

I'm trying to get a host's ip address using this code:

import os
import socket
ip = socket.gethostbyname(os.environ['COMPUTERNAME'])

the problem is that this host has VMware installed and the IP I get with the code above is that belonging to VMware, and not to the host. How can I fix this without uninstalling VMware? :P

jpaugh
  • 6,634
  • 4
  • 38
  • 90
sooaran
  • 183
  • 1
  • 2
  • 13
  • First, there's not "the" IP address. A host can have several addresses at once. Next, what IP addresses do you expect? The ones of the client, the ones of the host, the ones of your DSL router, ...? – Thomas Weller Feb 15 '18 at 17:27
  • Do you mean *host* as in server, or *host* as in VM Host? Where are you running this? (VM Guest or VM Host?) Which IP address are you trying to get? (VM Guest or VM Host?) – jpaugh Feb 15 '18 at 17:27
  • @ThomasWeller I'm not sure the OP has a client in mind. Do you mean VM guest? – jpaugh Feb 15 '18 at 17:28
  • @ThomasWeller as I said at top, I expect the host ip address – sooaran Feb 15 '18 at 17:29
  • @jpaugh forget the VM, I'm not using it, I just have it installed and want MY host ip, as in ipconfig -> Wi-fi adapter. – sooaran Feb 15 '18 at 17:32
  • @sooaran So, all of this is happening on the physical machine? Okay. – jpaugh Feb 15 '18 at 17:33
  • 1
    Possible duplicate: https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics – Thomas Weller Feb 15 '18 at 17:34
  • @jpaugh exactly! And, to add more information, my script have to retrieve the host's ip address, independently if there's VMware, VirtualBox, etc... I mean, when I run the script in a machine named X, I have to get that physical machine's IP address – sooaran Feb 15 '18 at 17:36
  • @sooaran I got it. When a VM is installed, it installs a software NIC; so I do believe Thomas Weller's duplicate link will help you. You'll need to distinguish the NICs by device ID or MAC address, and then pick the right one. Alternately, you could get all the IP addresses, and filter them by the subnet you expect it to be on. – jpaugh Feb 15 '18 at 17:40
  • Possible duplicate of [How do I determine all of my IP addresses when I have multiple NICs?](https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics) – jpaugh Feb 15 '18 at 17:41
  • I edited to remove the ambiguity caused by having a problem caused by a VM on the *host OS*. I think that might be the reason for a downvote. – jpaugh Feb 15 '18 at 17:44
  • thanks @jpaugh , I'm already checking that question out . And probably follow your advice about filtering the ip addresses... – sooaran Feb 15 '18 at 17:50

1 Answers1

-1

if you are using Windows you can make this

iphost = socket.gethostbyname(socket.gethostname())