Reputation: 133
I am very new to python and I am having a problem with using socket module to set up TCP connections. Here is part of my code:
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print ("The Client is: ")
print (client.raddr)
print ("%s:%s has connected." % clinet_address)
client.send(bytes("Greetings from the cave!" + "Now type your name and press enter!"),"utf8")
addresses[client] = client_address
Thread(target = handle_client, args = (client,)).start()
at the code here:
client,client_address = SERVER.accept()
I try to make the variable 'client_address' store the IP address of the client, but while running it, it turns out getting nothing. This variable was not assigned any value at all. After I checked the value stored in 'client', I found this :
'<socket.socket fd=4, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('10.146.0.2', 33000), raddr=('104.38.51.137', 62283)>'
in the 'raddr' part, I found my client IP address and port, so why is that? I do remember the accept() function has two return valve. If there is really only one return value, how am I suppose to extract the client IP and port from this return valve?
just in case of need, I will also post my client code here:
import socket # Import Socket module
import time
myname = input ("input you username>>")
s = socket.socket() # Create a Socket object
ip= "35.200.59.31"
port = 33000 # setup port number
s.connect((ip, port))
s.send(bytes(myname, encoding="utf-8"))
print (s.recv(1024))
username=str(input("input user name>>"))
s.send(bytes(username))
flag=True
while flag:
signal=s.recv(1024)
if signal == (bytes("xxx", encoding = "utf-8")):
tosend=(input(">>>"))
s.send(bytes(tosend))
print (">>",tosend)
if tosend=="quit":
flag = False
else :
print (">>>",signal)
s.close()
Upvotes: 1
Views: 799
Reputation: 133
Thanks, everyone! my problem is basically solved. Here is the fixed codes:
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print ("The Client address is: ")
print (client_address[0])
print (str(client_address[0]) + " has connected.")
client.send(bytes("Greetings from the cave!" + "Now type your name and press enter!",'utf8'))
addresses[client] = client_address[0]
Thread(target = handle_client, args = (client,)).start()
Though there are still a few other problems(probably logic problems), at least it will compile and run now. Again, thanks!
Upvotes: 1