Skip to content
Advertisement

Cannot connect to socket on ” ip address. Python

He, I have a server python script that listens on ip address '' and port 1337 and now I am trying to connect on the client side to that socket. But for some reason I cannot do that. If i will change the binding address to "127.0.0.1" it will work just fine, but I have been told to use this ip address ''.

Can someone please explain me why this is heppening and what is this ip address mean?.

This is my server:

import socket
from threading import Thread

HOST = '' 
PORT = 1337

def main():
    try:
        s.bind((HOST, PORT))
    except socket.error as msg:
        print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()

    print('Socket bind complete')

    s.listen(10)
    print('Socket now listening')

    while 1:
        conn, addr = s.accept()
        print('Connected with ' + addr[0] + ':' + str(addr[1]))

        new_client = Thread(target=clientthread, args=(conn,))
        new_client.start()

    s.close()

if __name__ == "__main__":
    main()

This is my client:

import socket

HOST = ''
PORT = 1337

def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    print("Worked!")
    s.close()

if __name__ == "__main__":
    main

And this is the weeor that I am getting:

Traceback (most recent call last):
  File "C:UsersmagshimimDownloadsresponder_client.py", line 4, in <module>
    s.connect((HOST, PORT))
OSError: [WinError 10049] The requested address is not valid in its context

Advertisement

Answer

The IP address '' (i.e., wildcard) in the server code represents the any address. This means that the server will listen on all available network interfaces.

'' is equivalent to 0.0.0.0 and is used only in the server, not a client. For a client, it requires knowing the actual IP address of the server in order to connect to it.

Consequently, using the IP address 127.0.0.1 in the client code is already correct.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement