Search code examples
pythonamazon-ec2ip-addresshttpserver

Send HTTP request to server hosted on AWS EC2 instance


I'm trying to send an HTTP POST request from the client to a server hosted on my AWS EC2 instance. I get this error when I try to set up the server on AWS.

Traceback (most recent call last):
  File "testReceive_AWS.py", line 197, in <module>
    httpd = server_class((server_address), MyHandler)
  File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
    self.server_bind()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
    SocketServer.TCPServer.server_bind(self)
  File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
    self.socket.bind(self.server_address)
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address

Here's my code:

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler

    server_address = ('EC2 instance public ip address', 9000) 

    httpd = server_class((server_address), MyHandler)

    print time.asctime(), "Server Starts - %s:%s" % (server_address)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (server_address)

I've confirmed that the IP address is correct. What am I doing wrong?


Solution

  • You can only bind to the private IP address of an EC2 instance. The IP stack on an EC2 instance is unaware of the public IP, because that address is automatically and transparently translated to/from the instance's private IP address by the VPC Internet Gateway.

    Bind to the private address or whatever this library accepts as "any/all IPv4". Typically this is 0.0.0.0, sometimes *, but in this case, BaseHTTPServer expects an empty string.

    server_address = ('', 9000)