0

I finished working on a 2 player game with python-socket While I tested it locally on my computer it worked fine, so I tested the code on my laptop but it didn't work(the client couldn't connect to the host) when the laptop was the client and for some reason, it did when the laptop was the client. I tested it with my friend too but both when he was the host and I was- didnt work.

this is the code for the server:

    import socket
    import pickle
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    hostName = input('host name(if you are the host write "host"):')
    if hostName == "host":
        host = True
        hostname = socket.gethostname()
        s.bind((socket.gethostbyname(hostname), 4242))
        print(f"your host name is: {socket.gethostbyname(hostname)}")
    
        s.listen(1)
        conn, addr = s.accept()

    else:
        host = False
        s.connect((hostName,4242))

The error says that the client timeout when it tried to s.connect

Itay Tsuk
  • 83
  • 1
  • 7
  • 1
    What value are you putting for the hostname in the client side? – Chris Doyle Jul 03 '21 at 20:08
  • *it didn't work...* What exactly didn't work? Did you get an error message, or a time out, or something else? Please add these details to the question. – President James K. Polk Jul 03 '21 at 20:11
  • I'm just copy-paste after it prints the hostname, and send it to myself – Itay Tsuk Jul 03 '21 at 20:12
  • President James k. polk(nice name) I wrote at the end that I get timeout because the client don't connect to the host – Itay Tsuk Jul 03 '21 at 20:14
  • 1
    Ok so that will have you the name of the host running the server. Have you got that name in DNS or /etc/hosts etc, how is the client machine meant to convert the hostname to an IP address to make the connection? – Chris Doyle Jul 03 '21 at 20:38
  • The gethostbyname function gives my ip4 always. this is what I use to connect the host... – Itay Tsuk Jul 03 '21 at 21:07
  • Oops sorry, I missed the `gethostbyname` call. So are both the client and server on the same network? what happens if you try to telnet from the client machine to the host ip and port – Chris Doyle Jul 04 '21 at 15:06

1 Answers1

1

I tried your code on my laptop and it's working correctly. I think it's the firewall

check out this answer: python socket Windows 10 connection times out

Pravin
  • 11
  • 1
  • That fixed the problem I had when my computer was the host and the laptop was the client but when I tried to do this with my friend it didn't work again :/ – Itay Tsuk Jul 04 '21 at 08:54
  • Check if your friends firewall is also doing the same on his laptop – Pravin Jul 10 '21 at 16:35