Reputation: 161
I'm currently making a multiplayer game just for my friends and stuff using socket and pygame and stuff, and I've encountered a small problem. I've tried implementing custom lobby codes so you can join a person directly, but socket doesnt like when I use a hostname other than the one I get from socket.gethostname(). Here is the code I want to use:
Code = GenerateString(6, True, True)
Users = {} # saved list of CONN for messaging and stuff ("Username": CONN)
Rlist = {} # List of received messages (TotalM: [CONN, Message])
TotalM = 0 # total messages sent for indexing purposes
MaximumPlayers = 16
ConnectedPeople = len(Users) # people connected via socked
TotalPeople = 0 # total people playing (including host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((Code, 5001))
# ^^^^^ this is what gives me the error (line 55)
------------
Traceback (most recent call last):
File "C:\Users\me\PycharmProjects\PredatorPrey\main.py", line 55, in <module>
s.bind((Code, 5001))
socket.gaierror: [Errno 11001] getaddrinfo failed
I would assume the GenerateString() function isn't important but I'll put the code anyways:
def GenerateString(Length, DoLetters=True, DoNumbers=True): # for generating the join code
p = ""
Letters = string.ascii_uppercase
if DoLetters and not DoNumbers:
for i in range(Length):
p += random.choice(Letters)
elif DoNumbers and not DoLetters:
p = str(random.randint(1 * 10 ** (Length - 1), (1 * 10 ** Length) - 1))
elif DoNumbers and DoLetters:
for i in range(Length):
if random.randint(0, 1):
p += random.choice(Letters)
else:
p += str(random.randint(0, 9))
else:
print("Cannot generate string: something went wrong")
return p
The only two solutions I've come up with are:
The magical third option I'm looking for is being able to change the hostname to anything I want (such as a 6 digit string) and be able to have anyone connect to it. I came across a function called sethostname() but I have not a single clue as to how it works and I can't find any documentation about it, making me question whether it really exists; there's no mention of it in the socket library. So far I haven't gotten anywhere in terms of implementing socket, so switching to a different library is a viable option. I am also using pygame and threading if that helps.
Upvotes: 0
Views: 1193
Reputation: 598448
You are trying to bind()
a socket to a randomly generated string. That will never work. You can only bind a socket to a local IP address, or to a valid hostname that resolves to a local IP address.
For what you are attempting to do, you will need a centralized server that can map the generated lobby codes to specific clients. Then clients can ask the server who a given lobby code belongs to.
Upvotes: 2