im创建一个Android应用程序,通过WiFi将套接字包链接到服务器。为此,必须定义连接服务器的IP地址。我使用以下功能获取IP地址。当我对server_ip =" 0"编码时;该应用程序正常运行。请帮助!
private final String SERVER_IP = getIpAddr();
public String getIpAddr() {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return ipString;
}
设置上述内容后,我在ongreate函数上运行了以下代码。
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
发生这种情况,我的Android应用程序将停止工作。
这是出现的错误:
java.lang.nullpointerexception:尝试调用虚拟方法'android.content.context android.content.content.context.getapplicationcontext(('null对象引用
使用此功能在活动中获取IP(V4或V6(:
// Get IP address from first non-localhost interface
// @param ipv4 true returns ipv4
// false returns ipv6
// @return address or empty string
public static String getLocalIpAddress(boolean useIPv4) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
当您需要时,只需以这种方式调用:getLocalIpAddress(true)
。您将获得IP作为字符串供您使用。
以下是您必须检查的几件事
- 该应用程序是否有权访问WiFi?
- 如果您在其他类中使用getApplicationContext((,请传递父活动的上下文。
- 在不在模拟器上的移动设备上进行测试。