Search code examples
pythonpython-3.xsocketstcpfileserver

module 'socket' has no attribute 'getsockname'


This is a simple file server file using TCP sockets, when i'm running this i'm getting the following error. Can anyone tell me the solution to this

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = socket.getsockname() # Reserve a port for your service.
block_size = 1024           #file is divided into 1kb size

s.bind((host, port))        # Bind to the port
#f = open('paris.png','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print('Got connection from', addr)
    print("Receiving...")
    l = c.recv(block_size)
    while (l):
        print("Receiving...")
        l = c.recv(block_size)
    #f.close()
    print("Done Receiving")
    mssg = 'Thank You For Connecting'
    c.send(mssg.encode())
    c.close()                # Close the connection


Traceback (most recent call last):
File "C:\Users\Hp\Documents\Python  codes\file_transfer_simple_server.py",line 5, in <module>
port = socket.getsockname() # Reserve a port for your service.
AttributeError: module 'socket' has no attribute 'getsockname'

Solution

  • As @Mark Tolonen mentioned in the comment, You were calling getsockname() on the socket module. getsockname is a method on the socket instance s

    import socket               
    
    s = socket.socket()         
    s.bind(('localhost',12345))
    host, port = s.getsockname() # unpack tuple
    block_size = 1024           
    
    print(port)
    # output
    12345