能否把改成 bind的ip地址通过参数输入? 比如 python server.py 192.168.0.1, python client.py 192.168.0.1,
时间: 2024-09-24 15:29:50 浏览: 44
当然可以。在Python中,你可以通过命令行参数的方式动态设置bind的IP地址。这样当运行服务器端程序时,可以接受一个参数作为IP地址。以下是修改后的`udp_server.py`示例:
```python
import socket
def start_server(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((host, port))
print(f"Server started on {host}:{port}")
while True:
data, address = server_socket.recvfrom(1024)
print(f"Received message from {address}: {data.decode()}")
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python server.py <IP_address>")
else:
host = sys.argv[1]
start_server(host, 12345) # 假设此处是默认端口,实际项目中可能需要从配置文件或其他地方获取
```
在客户端`udp_client.py`中,保持原样接收服务器的地址,但可以通过命令行传递IP地址给它:
```python
import socket
def send_message(host, port, message):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.sendto(message.encode(), (host, port))
print(f"Message sent to {host}:{port}")
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python client.py <IP_address> <message>")
else:
host = sys.argv[1]
message = sys.argv[2]
send_message(host, 12345, message)
```
运行服务器时,使用`python server.py 192.168.0.1`,运行客户端时,使用`python client.py 192.168.0.1 "Hello Server"`。
阅读全文