- 1 year ago
How to get the real ip of Windows from an Android app running on Windows subsystem for Android?
If you are running an Android app on Windows Subsystem for Android (WSA), and you want to get the real IP address of the Windows host machine from the Android app, you can use the following approach:
Use the
InetAddress
class in Android to resolve the IP address of the Windows machine.Get the hostname of the Windows machine using the
gethostname
function from the<winsock2.h>
header in C++.Call the
gethostbyname
function from the same header to resolve the hostname to an IP address.
Here's some example code that demonstrates this approach:
javatry {
// Get the hostname of the Windows machine
String hostname = InetAddress.getLocalHost().getHostName();
// Resolve the hostname to an IP address
InetAddress[] addresses = InetAddress.getAllByName(hostname);
// Print the IP addresses
for (InetAddress address : addresses) {
System.out.println(address.getHostAddress());
}
} catch (UnknownHostException e) {
// Handle error
}
In C++, you can use the following code:
cpp#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
int main() {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
char hostname[1024];
gethostname(hostname, 1024);
struct hostent* host = gethostbyname(hostname);
if (host == NULL) {
// Handle error
return 1;
}
struct in_addr** addr_list = (struct in_addr**)host->h_addr_list;
for (int i = 0; addr_list[i] != NULL; i++) {
std::cout << inet_ntoa(*addr_list[i]) << std::endl;
}
WSACleanup();
return 0;
}
This code uses the inet_ntoa
function to convert the resolved IP addresses to strings, which are then printed to the console.
Note that you will need to include the appropriate headers and link against the Ws2_32.lib
library to use the Windows networking functions.