0

I made a server in python, that after an incoming HTTP request it sends requests to other servers. Sometimes it's the case that it sends a request to himself, which causes a problem. Is there a way to detect if an IP address is it's own address?

It's running in a virtual machine in a cloud, without access to the outside Internet. So is there a way to detect that for example 10.158.3.251:5555 is the localhost of the machine running the code?

Edit: Getting the IP address now from ifconfig command. It feels clumsy, but it's working:

cmd = "/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"
self.ip = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]

Open for better solutions, problem is that the expected mapping (10.158.3.250 virtual-158-3-250.xxx.xx) is not in the /etc/hosts file.

Lodewijck
  • 364
  • 6
  • 19

2 Answers2

0
 import socket
 from socket import *
 myip = gethostbyname(gethostname())
 if(myip == destip):
   #do whatever
Josh Allemon
  • 842
  • 7
  • 8
0

I think the best way to do that is simply to check if the address happens to be one of the host's addresses. As mentioned in this post, you can get a list of your host's IP addresses in a number of ways, but I particularly like this method:

import socket
ips = socket.gethostbyname_ex(socket.gethostname())[2]

Now you can check if the given IP happens to be in the list. As to gethostbyname(gethostname()), this seems like a partial solution, as it does not return a full list of addresses (when I used it I only got an APIPA address).

Community
  • 1
  • 1
SivanBH
  • 392
  • 3
  • 13
  • Works like a charm on my local machine, but if I run this in the python terminal on my VM it gives: socket.gaierror: [Errno -2] Name or service not known. Any idea why? – Lodewijck Jul 22 '15 at 14:16
  • To be honest, no. But let's try to simplify this. Try to separate the 2 function calls. Call `socket.gethostname()` first, make sure it returns a legitimate value, and then call `socket.gethostbyname_ex()` with that said value. – SivanBH Jul 22 '15 at 14:30
  • socket.gethostname() -> 'virtual-158-3-250.xxx.xx', socket.gethostbyname_ex('virtual-158-3-250.xxx.xx') -> Unknown, socket.gethostbyaddr('10.158.3.250') -> Unknown, I just have to find a way to detect that virtual-158-3-250.xxx.xx is the same as 10.158.3.250. But how? – Lodewijck Jul 22 '15 at 14:57
  • 2
    That could be the result of a badly configured hosts file. In your hosts file, there should be an entry mapping 127.0.0.1 to localhost, and an entry mapping your "real" IP address to your host name (`10.158.3.250 virtual-158-3-250.xxx.xx`). If you're on a Windows machine, the file can be found in "C:\Windows\System32\drivers\etc\hosts". If you're on a Linux machine, the file is located at /etc/hosts. – SivanBH Jul 22 '15 at 15:09