【问题标题】:module 'socket' has no attribute 'getsockname'模块“socket”没有属性“getsockname”
【发布时间】:2019-04-02 00:17:47
【问题描述】:

这是一个使用 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'

【问题讨论】:

  • 您在 socket 模块上调用了 getsockname()getsockname 是套接字实例s 上的一个方法。

标签: python python-3.x sockets tcp fileserver


【解决方案1】:

正如@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

【讨论】:

  • 那么有没有任何方法可以生成/分配随机端口号,这样就不应该与已经分配给正在运行的应用程序的端口号发生冲突@sufiyan-ghori
猜你喜欢
  • 2021-10-21
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2021-12-24
相关资源
最近更新 更多