这是使用TCP套接字的简单文件服务器文件,
当我运行此程序时,出现以下错误。
谁能告诉我解决方案

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'

最佳答案

正如@Mark Tolonen在评论中提到的那样,您正在套接字模块上调用getsockname()getsockname是套接字实例s上的方法

import socket

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

print(port)
# output
12345

09-27 17:30