我目前正在使用python中的套接字库将基本文本从一台计算机发送到同一局域网中的另一台计算机。
我的问题是,由于我多次使用不同的计算机,因此客户端连接的iPv4每次都会更改。
客户代码的第4行:client.connect(("172.16.0.34",8888))
这带来了一个困难,因为我无法轻松更改客户端代码中的ip。
我的问题:
客户端是否可能有一种方式可以“扫描”网络以查看托管套接字的IP并获取该IP以连接到它们,从而允许我使用任何计算机并使其仍在运行?
这是我的代码:
客户:
import socket
client = socket.socket()
try:
client.connect(("172.16.0.34",8888))
except:
print("Server not connected")
else:
print("Connect to server: ","localhost")
while True:
print("[Waiting for response...]")
print(client.recv(1024))
valid = False
while not valid:
try:
msg = str(input("Enter your message to send: "))
except:
print("Invalid input format")
else:
valid = True
to_send = msg.encode("UTF-8")
client.send(to_send)
服务器:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created")
host = "0.0.0.0"
port = 8888
print(host)
try:
server.bind((host,port))
except:
print("Bind failed")
else:
print("Bind successful")
server.listen(5)
clientsocket = None
while True:
if clientsocket == None:
print("[Waiting for connection..]")
(clientsocket, address) = server.accept()
print("Client accepted from", address)
else:
print("[Waiting for response...]")
print(clientsocket.recv(1024))
valid = False
while not valid:
try:
msg = str(input("Enter your message to send: "))
except:
print("Invalid input format")
else:
valid = True
clientsocket.send(msg.encode("UTF-8"))