android java 获得本机ip_android java获取服务器ip 本机ip、mac地址

获取服务器ip:

byte data[] = new byte[packageSize];

DatagramPacket dp = new DatagramPacket(data, data.length);

ms.receive(dp);

serviceIpAddress = dp.getAddress().toString();

serviceIpAddress = serviceIpAddress.substring(1, serviceIpAddress.length());

获取本机ip、mac地址:

// 在wifi未开启状态下,仍然可以获取MAC地址,但是IP地址必须在已连接状态下否则为0

String macAddress = null, ip = null;

WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);

WifiInfo info = (null == wifiMgr ? null : wifiMgr

.getConnectionInfo());

if (null != info) {

macAddress = info.getMacAddress();

ip = intToIp(info.getIpAddress());

}

System.out.println("mac:" + macAddress + ",ip:" + ip);

private String intToIp(int i) {

return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."

+ (i >> 24 & 0xFF);

}

你可能感兴趣的:(android,java,获得本机ip)