Using public IP address in sockets

馋奶兔 提交于 2021-02-08 10:51:37

问题


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()

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


回答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.

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".

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



来源:https://stackoverflow.com/questions/55198388/using-public-ip-address-in-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!