将php中$report['user_agent'] = env('HTTP_USER_AGENT');转成Python socket
时间: 2024-01-26 08:04:55 浏览: 85
在 Python socket 中,获取客户端的 User-Agent 可以通过 HTTP 请求头中的 User-Agent 字段获得。以下是一个示例代码:
```python
import socket
HOST = 'localhost'
PORT = 8000
def handle_request(client_socket):
request_data = client_socket.recv(1024)
headers = request_data.decode().split('\r\n')
user_agent = None
for header in headers:
if header.startswith('User-Agent:'):
user_agent = header.split(': ')[1]
break
response_body = f'<html><body><h1>User-Agent: {user_agent}</h1></body></html>'
response_headers = [
'HTTP/1.1 200 OK\r\n',
'Content-Type: text/html; charset=utf-8\r\n',
f'Content-Length: {len(response_body)}\r\n',
'\r\n',
]
response = ''.join(response_headers) + response_body
client_socket.send(response.encode())
client_socket.close()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f'Server is listening on {HOST}:{PORT}')
while True:
client_socket, client_address = server_socket.accept()
print(f'Accepted connection from {client_address[0]}:{client_address[1]}')
handle_request(client_socket)
```
这里用一个 handle_request 函数来处理每个客户端请求。首先从请求数据中解析出所有请求头,然后找到 User-Agent 字段并提取出来。最后返回一个包含 User-Agent 的 HTML 页面作为响应。
阅读全文