3 # wpa_supplicant/hostapd control interface using Python
4 # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
6 # This software may be distributed under the terms of the BSD license.
7 # See README for more details.
17 def __init__(self, path, port=9877):
25 mode = os.stat(path).st_mode
26 if stat.S_ISSOCK(mode):
34 self.s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
36 self.local = "/tmp/wpa_ctrl_" + str(os.getpid()) + '-' + str(counter)
38 self.s.bind(self.local)
40 self.s.connect(self.dest)
47 ai_list = socket.getaddrinfo(path, port, socket.AF_INET,
49 for af, socktype, proto, cn, sockaddr in ai_list:
50 self.sockaddr = sockaddr
52 self.s = socket.socket(af, socktype)
54 self.s.sendto("GET_COOKIE", sockaddr)
55 reply, server = self.s.recvfrom(4096)
59 print "connect exception ", path, str(port)
73 # Need to ignore this allow the socket to be closed
82 def request(self, cmd, timeout=10):
84 self.s.sendto(self.cookie + cmd, self.sockaddr)
87 [r, w, e] = select.select([self.s], [], [], timeout)
89 return self.s.recv(4096)
90 raise Exception("Timeout on waiting response")
95 res = self.request("ATTACH")
99 raise Exception("ATTACH failed")
102 if not self.attached:
104 while self.pending():
106 res = self.request("DETACH")
107 if "FAIL" not in res:
108 self.attached = False
110 raise Exception("DETACH failed")
117 # Need to ignore this to allow the socket to be closed
118 self.attached = False
119 self.request("TERMINATE")
122 def pending(self, timeout=0):
123 [r, w, e] = select.select([self.s], [], [], timeout)
129 res = self.s.recv(4096)