pythonpython-3.xsocketsserversocketpeer

how to get Ip address of client after connection is established in python socket programming?


I wrote a socket program to send a file and receive a string from socket In which I specified the client(wrote the ip address of client) I want to get that client address dynamically, I tried .getpeername() function but getting error

I tried .getpeername() function but getting error

#host = '10.66.227.181'   # fixed ip of one client only
client_socket = socket.socket()
host = client_socket.getpeername()
print(clientip)
port = 8000
print(host,port)
client_socket.connect(host,port)

clientip = socket.gethostname(client_socket.getpeername()) OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied


Solution

  • If a UDP socket isn't connected there is no peer. So there can't be a peer name. And if it is connected, you already know how you connected it to.

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(host,port)
    host, port = client_socket.getpeername()