ObtainIps

public class ObtainIps {
private Context context;
static public HashMap<String, String> ping; // ping 后的结果集
// 当前线程的数量, 防止过多线程摧毁电脑
static int threadCount = 0;
public HashMap<String, String> getPing() { // 用来得到ping后的结果集
return ping;
}


public ObtainIps(Context context) {
this.context = context;
ping = new HashMap<String, String>();
}


public void Ping(String ip) throws Exception {
// 最多10个线程
while (threadCount > 10)
{
Thread.sleep(50);
}
threadCount += 1;
PingIp p = new PingIp(ip);
p.start();
}


public void PingAll() throws Exception 
{
// 首先得到本机的IP,得到网段
String hostAddress = getip();
if (CommonUtil.isEmpty(hostAddress) || hostAddress.equals("0.0.0.0")) 
{
hostAddress = "192.168.0";
}
CommonUtil.log("hostAddress -->"+hostAddress);
int k = 0;
k = hostAddress.lastIndexOf(".");
String ss = hostAddress.substring(0, k + 1);
for (int i = 2; i <= 255; i++) 

// 对所有局域网Ip
String iip = ss + i;
Ping(iip);
}


// 等着所有Ping结束
while (threadCount > 0)
{
Thread.sleep(50);
}
}

public List<String> startObtainIps()
{
List<String> ips = new ArrayList<String>();
ObtainIps ip = new ObtainIps(context);
try 
{
ip.PingAll();
Set<Entry<String, String>> entries = (Set<Entry<String, String>>) ping.entrySet();
Iterator<Entry<String, String>> iter = entries.iterator();
while (iter.hasNext()) 
{
Entry<String, String> entry = (Entry<String, String>) iter.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();


if (value.equals("true"))
{
ips.add(key);
}
}

catch (Exception e) 
{
e.printStackTrace();
}
return ips;
}


class PingIp extends Thread 
{
public String ip; // IP


public PingIp(String ip) 
{
this.ip = ip;
}


public void run()
{
try 
{
Process p = Runtime.getRuntime().exec("ping -c 1 -w 5 " + ip);
int status = p.waitFor();
if (status == 0) 
{
ping.put(ip, "true");

//添加socket连接测试
// InetAddress serverAddr = InetAddress.getByName(ip);// m_serveraddr为机顶盒ip
// Socket socket_air = new Socket(serverAddr, Constant.SOCKET_PORT); // 创建socket
// if (socket_air.isConnected()) {
// ping.put(ip, "true");
// }
// else
// {
// ping.put(ip, "false");
// }

else 
{
ping.put(ip, "false");
}
// 线程结束
threadCount -= 1;

catch (Exception e) 
{
System.out.println(e.toString());
}
}
}

public String getip()
{
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) 
{
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ip = intToIp(wifiInfo.getIpAddress());
return ip;
}


// 获取IP地址
private String intToIp(int i)
{
return (i & 0XFF) + "." + ((i >> 8) & 0XFF) + "." + ((i >> 16) & 0XFF) +"." + ((i >> 24) & 0XFF);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值