简体   繁体   中英

Connecting AWS EC2 instance using Python Socket

Server.py (Running on my aws ec2 instance)

import socket

s = socket.socket()
host = socket.gethostbyaddr('aws.ec2.public.ip')[0]
port = 12345
s.bind((host, port))

s.listen(5)
while True:
   c, addr = s.accept()
   print('Got connection from', addr)
   c.send('Thank you for connecting'.encode())
   c.close()

Client.py (Running on my local pc)

import socket

s = socket.socket()
host = socket.gethostbyaddr('aws.ec2.public.ip')[0]
port = 12345

s.connect((host, port))
print(s.recv(1024).decode())
s.close()

All inbound & outbound TCP traffic granted

The Server code shows no error. But the Client code says

Traceback (most recent call last):
  File "/Users/sohamjain/Desktop/client.py", line 7, in <module>
    s.connect((host, port))
TimeoutError: [Errno 60] Operation timed out
>>> 

Connecting to the EC2 instance via rdp client works perfectly

When I run both these scripts on local host they seem to work fine. But in case of AWS EC2 Instance, it does not. Where did I go wrong?

I have just encountered your situation:

As Chris Williams mentioned in a reply to your question, you cannot use the public IP address when binding the listening socket on the EC2 instance. Change that to use the private IP and it should work.

Also make sure you enable traffic for the port you are binding from AWS security groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM