# Best way to automate connecting to a wifi network



## kpedersen (Oct 19, 2009)

Hello,

Because I connect to many different wireless networks around work, very often and there is no decent GUI/CUI, I currently have a few scripts that I run as su which look a little like this...


```
wpa_supplicant -i ath0 -c /etc/wpa_supplicant_lab7.conf & dhclient ath0
```

Now, this sometimes fails because dhclient times out before wpa_supplicant has made a connection...

Does anyone have any suggestions of how best to do this?

Personally OpenBSD has a great solution of allowing wpa to be configured in their ifconfig. However, I generally prefer FreeBSD  (packages are more plentyful for one!)

Best Regards,

Karsten

EDIT: Sorry, this should be in the mobile computing section


----------



## DutchDaemon (Oct 19, 2009)

Did you mean 
	
	



```
wpa_supplicant -i ath0 -c /etc/wpa_supplicant_lab7.conf [B][color="Red"]&&[/color][/B] dhclient ath0
```
?

I don't know if wpa_supplicant stays in the foreground until it has a connection, but your single '&' backgrounds it immediately. You'd want wpa_supplicant to finish before dhclient tries to get an IP address.


----------



## kpedersen (Oct 19, 2009)

Hmm, the thing is that wpa_supplicant never actually finishes, even after it is successful, it keeps running to maintain the connection.

I could use -B to make wpa_supplicant into a daemon, but then the same problem occurs and dhclient might fail.

Or will wpa_supplicant return success even though it is still running? I will give it a go as soon as I can.


----------



## DutchDaemon (Oct 19, 2009)

I have no idea. You could background it, sleep for xx seconds (that's a matter of trial and error), and then run dhclient. 


```
wpa_supplicant -i ath0 -c /etc/wpa_supplicant_lab7.conf &
sleep xx
dhclient ath0
```

Or if you know how to establish the existence of a connection, throw in a loop.


```
wpa_supplicant -i ath0 -c /etc/wpa_supplicant_lab7.conf &
while true do
if [ the connection exists ]
then
dhclient ath0
exit 0
else
sleep 10
fi
done
```


----------



## aragon (Oct 19, 2009)

What about rc?


```
/etc/rc.d/wpa_supplicant start atho
```


----------



## kpedersen (Oct 20, 2009)

That unfortunately will cause the same problem with getting dhclient to run just whan it has connected.

What I am currently doing is (based on DutchDaemon's wait loop)


```
ifconfig ath0 | grep "status: associated"
```

and looping (with a small sleep) until this stops returning nothing.

Fully hacky!


----------

