Search code examples
socketspython-3.xclientserver

Python 3 Using Sockets over the Internet


I have been trying to set up sockets that will work over the internet. I have search high and low through stack overflow and cannot seem to find the answer I need.

When I run server.py I receive this error:

Traceback (most recent call last):
  File "server.py", line 16, in <module>
    serversocket.bind((host, port))
OSError: [WinError 10049] The requested address is not valid in its context

Note that the following seems to work over local wifi.

The server code:

# server.py 
import socket                                      

# create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 


#get ip address
print("You are the server.")
print("What is your ip? If you do not know, look up <my ip> on google.")
host = input(">")                         

port = 0                                          

# bind to the port
serversocket.bind((host, port))                                  

# queue up to 5 requests
serversocket.listen(5)   
clientsocket,addr = serversocket.accept()                                          

def messenger():
    # establish a connection    
    tm = clientsocket.recv(1024)
    tm = tm.decode('ascii')

    if tm == "9+10":
        message = "21"
    elif tm == "sweg":
        message = "swegedy swooty feel the booty"
    else:
        message = "feggeet"
    clientsocket.send(message.encode('ascii'))
    messenger()
messenger()

The client side code:

# client.py  
import socket

#get ip address
print("You are the client.")
print("What is your servers ip?")
host = input(">")  

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

port = 0
s.connect((host, port))

# Receive no more than 1024 bytes
def messenger():
    message = input("command:")
    s.send(message.encode("ascii"))
    tm = s.recv(1024)                                     
    print(tm.decode('ascii'))
    messenger()
messenger()

From what I have learned, this should work as long as I insert a public IP address. However, I just get that error message.

What am I doing wrong?


Solution

  • Your server can only bind to a host address upon which it is located. IIRC, you should bind to 0.0.0.0, this binds to all addresses on the current machine. You can then connect the client locally (same machine 127.0.0.1, local machine - you'll need to know the internal IP address of the machine).

    Correction, the common method is serversocket.bind((socket.gethostname(), 80))

    If you want to access it from the internet the first thing you'll need to know is the internet address of you machine. Since it's unlikely that you're connected directly to the internet, this will like be the IP address of your router.

    The next step will be to allow port forwarding through the router to your machine - again, a huge treatise can be written about this.