在套接字中使用公共 IP 地址 [英] Using public IP address in sockets

查看:82
本文介绍了在套接字中使用公共 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是套接字编程的新手.我的套接字使用 localhost 或本地 ip.但是为什么我不能用我的公共 ip 创建一个套接字服务器?当我尝试在 python 中执行此操作时,它抱怨无法分配请求的地址".

I am new to socket programming. My sockets work with localhost or local ip. But why can't I create a socket server with my public ip? When I try to do this in python, it complains "cannot assign requested address".

import socket
s=socket.socket()
host="address"
port=5000
s.bind((host, port))
s.listen(5)
while True:
    c, addr=s.accept()
    result=c.recv(1024)
    print(result.decode('utf-8'))
    c.send("""
  test
""".encode('utf-8'))
    c.close()

我从这个网站获得的 IP:http://whatismyip.host/

My IP I got from this website:http://whatismyip.host/

推荐答案

http://whatismyip.host/ 将显示路由器的公共地址,即连接到互联网的机器.如果您查找台式机的 IP,它可能会显示类似 192.168.0.10 的内容,其中 192.168.0.1 是您在路由器中输入的路由器地址桌面,作为网关".

A service like http://whatismyip.host/ will show you the public address of your router, that is the machine that is connected to the internet. If you look up the IP of your desktop machine, it will probably show something like 192.168.0.10, with 192.168.0.1 being the address of your router that you enter in your desktop, as "gateway".

您的路由器类似于防火墙,将您的家庭网络与公共互联网分开.

Your router resembles a firewall, separating your home network from the public internet.

为了在台式机上接收连接,您需要在路由器上配置端口转发.你仍然会让你的 python 进程监听 192.168.0.10(你的本地机器的 IP).或者您可以将其设置为 0.0.0.0,这是所有可用接口"的简写.

In order to receive connections on your desktop machine, you would need to configure port forwarding on your router. You will still have your python process listen on 192.168.0.10 (your local machine's IP). Or you could set it to 0.0.0.0 which is a shorthand for "all available interfaces".

请注意,您的公共 IP 地址可能不稳定.

Be aware that your public IP address is probably not stable.

这篇关于在套接字中使用公共 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆