I am making a program in Java where it needs to print out a list of available WiFi's names, the SSID, into the console all separated by semicolons.
So like: wifi1;thekingswifi;otherwifi
I am making a program in Java where it needs to print out a list of available WiFi's names, the SSID, into the console all separated by semicolons.
So like: wifi1;thekingswifi;otherwifi
Querying the wifi data on a system is sadly OS specific so there isn't a common library to do this.
Nevertheless, here's a class that I wrote that uses the windows command line utility netsh to retrieve the SSID's and return them in a JSON string. There are similar utilities on the other operating systems that you can use to achieve the same effect. Hopefully this class will get you started.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WindowsNetworkHelper
{
public String getSsidsJson(String regex) throws Exception
{
Runtime rt = Runtime.getRuntime();
try
{
Process pr = rt.exec("netsh wlan show networks mode=bssid");
String processOutput = processOutputToString(pr);
ArrayList<String> ssidList = extractSsids(processOutput,regex);
String result = "[";
boolean addComma = false;
for(String ssid : ssidList)
{
if(addComma)
{
result += ",";
}
result += "{\"ssid\":\"" + ssid + "\"}";
addComma = true;
}
result += "]";
return result;
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "[]";
}
private ArrayList<String> extractSsids(String result,String regex)
{
ArrayList<String> ssids = new ArrayList<String>();
String[] lines = result.split("\r\n\r\n");
Pattern ssidPattern = Pattern.compile("^SSID [0-9]+ : (.+)");
for(String line : lines)
{
Matcher ssidMatcher = ssidPattern.matcher(line);
if(ssidMatcher.find())
{
String capture = ssidMatcher.group(1);
if(ssidMatchesFilter(capture,regex))
{
ssids.add(capture);
}
}
}
return ssids;
}
private boolean ssidMatchesFilter(String ssid,String regex)
{
if(regex == null)
{
return true;
}
Pattern filterPattern = Pattern.compile(regex);
Matcher filterMatcher = filterPattern.matcher(ssid);
return filterMatcher.matches();
}
private String processOutputToString(Process pr)
{
InputStream is = pr.getInputStream();
java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
s.close();
return result;
}
}