[英]Connecting AWS EC2 instance using Python Socket
Server.py (Running on my aws ec2 instance) Server.py(在我的 aws ec2 实例上运行)
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) Client.py(在我的本地电脑上运行)
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
授予所有入站和出站 TCP 流量
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
通过 rdp 客户端连接到 EC2 实例完美运行
When I run both these scripts on local host they seem to work fine.当我在本地主机上运行这两个脚本时,它们似乎工作正常。 But in case of AWS EC2 Instance, it does not.
但在 AWS EC2 实例的情况下,它不会。 Where did I go wrong?
我在哪里 go 错了?
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.正如 Chris Williams 在回答您的问题时提到的那样,在 EC2 实例上绑定侦听套接字时,您不能使用公共 IP 地址。 Change that to use the private IP and it should work.
将其更改为使用私有 IP 并且它应该可以工作。
Also make sure you enable traffic for the port you are binding from AWS security groups.还要确保从 AWS 安全组为您绑定的端口启用流量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.