python 套接字编程中建立连接后如何获取客户端的IP地址?

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

我写了一个套接字程序来发送一个文件并从套接字接收一个字符串 我在其中指定了客户端(写了客户端的IP地址) 我想动态获取那个客户端地址, 我尝试了 .getpeername() 函数但出现错误

我尝试了 .getpeername() 函数但出现错误

#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)

客户端提示 = socket.gethostname(client_socket.getpeername()) OSError:[WinError 10057] 不允许发送或接收数据的请求,因为套接字未连接并且(当使用 sendto 调用在数据报套接字上发送时)没有提供地址

如果 UDP 套接字未连接,则没有对等点。所以不可能有对等名称。 如果已连接,您已经知道如何连接它了。

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

这是 'Foundations of Python Network Programming' 书中关于 udp 套接字(服务器端和客户端)的示例,我认为这个示例对您有用:

import argparse, socket
from datetime import datetime

MAX_BYTES = 65535

def server(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('127.0.0.1', port))
    print('Listening at {}'.format(sock.getsockname()))
    while True:
        data, address = sock.recvfrom(MAX_BYTES)
        text = data.decode('ascii')
        print('The client at {} says {!r}'.format(address, text))
        text = 'Your data was {} bytes long'.format(len(data))
        data = text.encode('ascii')
        sock.sendto(data, address)

def client(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    text = 'The time is {}'.format(datetime.now())
    data = text.encode('ascii')
    sock.sendto(data, ('127.0.0.1', port))
    print('The OS assigned me the address {}'.format(sock.getsockname()))
    data, address = sock.recvfrom(MAX_BYTES)  # Danger! See Chapter 2
    text = data.decode('ascii')
    print('The server {} replied {!r}'.format(address, text))

if __name__ == '__main__':
    choices = {'client': client, 'server': server}
    parser = argparse.ArgumentParser(description='Send and receive UDP locally')
    parser.add_argument('role', choices=choices, help='which role to play')
    parser.add_argument('-p', metavar='PORT', type=int, default=1060,
                        help='UDP port (default 1060)')
    args = parser.parse_args()
    function = choices[args.role]
    function(args.p)

source

由于“主机”术语,上述答案会让大多数人感到困惑,所以这里有一个更好的答案:

ip_address = my_socket.getpeername()[0]

其中 my_socket 是您已经设置和连接的套接字的句柄。