python通过建立长链接,获取动态ip,这种方式可以长时间保持连接
服务端 server.py
# 服务端 import socket class UdpServer(object): def tcpServer(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind(('0.0.0.0', 1060)) while True: revcData, (remoteHost, remotePort) = sock.recvfrom(1024) print("[%s:%s] connect" % (remoteHost, remotePort)) sendDataLen = sock.sendto("this is send data from server".encode(), (remoteHost, remotePort)) print("revcData: ", revcData) print("sendDataLen: ", sendDataLen) sock.close() if __name__ == "__main__": udpServer = UdpServer() udpServer.tcpServer()
客户端:client.py
# 客户端 from socket import * import time # 设定目标地址 dest = ('<broadcast>', 1060) s = socket(AF_INET, SOCK_DGRAM) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) data = 'Is client,time of {}'.format(time.time()) str = s.sendto(data.encode('utf-8'), dest) # 发送广播 s.settimeout(30) # 设置等待超时时间为30s msg, addr = s.recvfrom(1024) # recvfrom为阻塞方法 print('接收回复==服务端地址:{},响应内容:{}'.format(addr, msg.decode('utf-8'))) s.close()
使用方法如下,在使用过程中,先启动服务端程序,然后如果客户端那里需要此ip,可以当即运行客户端代码,进行获取