I'm writing an Android video game that supports multiplayer. There is a dedicated server running which the androids connect to when the multiplayer button is clicked by opening a socket(this works fine). The server basically just acts as a matchmaking system.
When a client hosts a game, the server adds that client to the list of hosts. Other clients may choose to view this list and then subsequently connect to that host. This is where the problem is. The server is supposed to keep track of the ip/port of hosts, and then other clients are supposed to use this information to open a socket with the host and then the game starts. I'm trying to get the host to send its own IP address to server for other clients to use later.
I have tried many methods so far. One is:
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
}
This returns 10.0.2.15, which is obviously useless for other clients.
The other method I've tried is this:
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
for (InetAddress addr: addrs) {
System.out.println ("addr.getHostAddress() = " + addr.getHostAddress());
System.out.println ("addr.getHostName() = " + addr.getHostName());
System.out.println ("addr.isAnyLocalAddress() = " + addr.isAnyLocalAddress());
System.out.println ("addr.isLinkLocalAddress() = " + addr.isLinkLocalAddress());
System.out.println ("addr.isLoopbackAddress() = " + addr.isLoopbackAddress());
System.out.println ("addr.isMulticastAddress() = " + addr.isMulticastAddress());
System.out.println ("addr.isSiteLocalAddress() = " + addr.isSiteLocalAddress());
System.out.println ("");
if (!addr.isLoopbackAddress()){// && addr.isSiteLocalAddress()) {
myIP = addr.getHostAddress();
}
This returns the ip address that I'm looking for when I run it as a java application, but when I run it as an android application, it doesn't work. The last if condition is somehow not satisfied and myIP ends up being null. Note that I have included the permissions: android.permission.INTERNET, android.permission.ACCESS_WIFI_STATE, android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_NETWORK_STATE.
Can anybody help me?
If you just need the IP for the Wifi connection you can retrieve the IP as a 32 bit integer:
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
Then, in order to construct the IP in dot-decimal notation; bit-shift and mask the result:
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
android.permission.ACCESS_WIFI_STATE permission will be required in the manifest.
Do you have to rely on the host to figure out its own IP address and provide this to the server? If the host opens a connection and sends a message to the server announcing that it is hosting a game, then could the server use the IP address that the connection and message came from? This would avoid the problem altogether.
try this
WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE) ;
List<WifiConfiguration> l= wim.getConfiguredNetworks();
WifiConfiguration wc=l.get(0);
textview.append( "\n"+ Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress()));
Related
This question already has an answer here:
Android Quickly Find All Local Devices on Network
(1 answer)
Closed 6 years ago.
I am trying to code in android to return the name of all devices and their ip on the wifi. I am having trouble on how to approach this. All of the examples online return only the localhost and its information. i.e.
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(" IP Addr: " + localhost.getHostAddress());
// Just in case this host has multiple IP addresses....
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
System.out.println(" Full list of IP addresses:");
for (int i = 0; i < allMyIps.length; i++) {
System.out.println(" " + allMyIps[i]);
}
}
} catch (UnknownHostException e) {
System.out.println(" (error retrieving server host name)");
}
try {
System.out.println("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
System.out.println(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
System.out.println(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
System.out.println(" (error retrieving network interface list)");
}
This is not necessarily What I want, since I want to return all of the devices on the wifi.
I don't know how to go about this.
please help, thank you !
WifiManager This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:
The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
Results of access point scans, containing enough information to make decisions about what access point to connect to.
It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state.
WifiInfo Describes the state of any Wifi connection that is active or is in the process of being set up.
Example:
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
String macAddress = wifiInfo.getMacAddress();
Ensure you have modified your manifest with the following:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Sources:
1. WifiManager
2. WifiInfo API
In my Tomcat-hosted web app, the first two lines in a doGet(...) method are:
String ip = request.getRemoteAddr();
System.out.println("ip = " + ip);
With an IPv6 address on our local network, it outputs:
ip = fe80:0:0:0:ac40:98cb:ca2e:c03c%4
The %4 at the end seems extraneous. It is causing requests to our geolocation service to fail. Is this %4 supposed to be there? If so, what does it signify? Is there a reliable way to get a IPv6 address from an HttpServletRequest instance that does NOT have the %4?
It's the scope ID. Using native APIs, your best bet to get rid of it would be as below with help of java.net.InetAddress and Inet6Address#getScopeId():
String ip = request.getRemoteAddr();
InetAddress inetAddress = InetAddress.getByName(ip);
if (inetAddress instanceof Inet6Address) {
Inet6Address inet6Address = (Inet6Address) inetAddress;
int scopeId = inet6Address.getScopeId();
if (scopeId > 0) {
ip = inet6Address.getHostName().replaceAll("%" + scopeId + "$", "");
}
}
This clumsiness is because the standard java.net.Inet6Address API doesn't have any method which returns the bare hostname without scope ID.
On the other hand, I'd wonder if the geolocation service in question should in turn not already be taking that into account. If the support for IPv6 scopes is even not explicitly excluded in their API documentation, then I'd file an issue at their issue tracker.
I use inssider and kismac for checking the wifi indoor and outdoor accesspoints in my network. But both these tools doesn't provide any info on the ip of the access point currently connected. Its seen that netstumbler in windows had an option to display ip address and subnet but, though they have the fields, it doesn't display anything. I don't find any app that fulfills this requirement.
Is there any method to find the ip address of the nearest accesspoint in my wifi network? programmatically or is there any app?
is there any method in python , objective c , java where a request for ip-address of an ap returns it.
I use osx 10.9
use following way to achieve
public String getIpAddr() {
WifiManager wifiManager = (WifiManager) 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;
}
Please Note: You need to add android.permission.INTERNET and android.permission.ACCESS_WIFI_STATE in your AndroidManifest.xml as to access the code.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
for google play similar type of app look at https://play.google.com/store/apps/details?id=com.roamingsoft.manager&hl=en
You cant get ip of AP without connecting to it.
You can get ip of connected AP by following
DhcpInfo dhcp;
WifiManager wifii;
wifii = (WifiManager) getSystemService(Context.WIFI_SERVICE);
dhcp = wifii.getDhcpInfo();
s_dns1 = "DNS 1: " + String.valueOf(dhcp.dns1);
s_dns2 = "DNS 2: " + String.valueOf(dhcp.dns2);
s_gateway = "Default Gateway: " + String.valueOf(dhcp.gateway);
s_ipAddress = "IP Address: " + String.valueOf(dhcp.ipAddress);
s_leaseDuration = "Lease Time: " + String.valueOf(dhcp.leaseDuration);
s_netmask = "Subnet Mask: " + String.valueOf(dhcp.netmask);
s_serverAddress = "Server IP: " + String.valueOf(dhcp.serverAddress);
I have the following problem: I create an ArrayList and I put in this arraylist all the IP addresses of my client (one if the client have a single network card, n if the client run on a PC having n network card) excluding the loopback adress, the point to point adress and the virtual adress.
I have do this in this way:
private static List<String> allIps = new ArrayList<String>();
static {
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
while(nets.hasMoreElements()) {
NetworkInterface current = nets.nextElement();
if ((current.isUp()) && (!current.isPointToPoint()) && (!current.isVirtual()) && (!current.isLoopback())) {
System.out.println(current.getName());
Enumeration<InetAddress> ee = current.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = ee.nextElement();
System.out.println(i.getHostAddress());
allIps.add(i.getHostAddress());
}
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("List of all IP on this client: "
+ allIps.toString());
System.out.println("Number of ip: " + allIps.size());
}
It seems work well, the only problem is that my output (in the Eclipse console) is:
eth0
fe80:0:0:0:20c:29ff:fe15:3dfe%2
192.168.15.135
List of all IP on this client: [fe80:0:0:0:20c:29ff:fe15:3dfe%2, 192.168.15.135]
Number of ip: 2
Using the debugger and the console output appear clear to me that, in this case, the only network interface present is eth0 (and this is ok) but, for this network interface, id found 2 IP adresses (the fits one is IPV6 address, the second one is the classic IPV4 address)
So it put in my adresses list allIps both.
I want select and put in my allIps list only the IPV4 adresses and not also the IPV6. What can I do to do it? Can I filter and select only IPV4 on my InetAddress object?
Tnx
Andrea
Use instanceof and the Inet4Address type:
for (NetworkInterface ni :
Collections.list(NetworkInterface.getNetworkInterfaces())) {
for (InetAddress address : Collections.list(ni.getInetAddresses())) {
if (address instanceof Inet4Address) {
System.out.println(address);
}
}
}
I need to get computer IP from Ubuntu using Java. I tried with InetAddress.getLocalHost.getHostAddress().toString(); but it returns 127.0.0.1 . I was searching for solution and found out this code:
NetworkInterface ni = NetworkInterface.getByName("eth0");
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
System.out.println("IP: " + ia.getHostAddress());
}
}
}
This code worked for me but problem is when computer uses "eth1" interface or computer can use wireless adapter to connect to network (wlan0). On that situatuon program will fail. Can you guys advise me with safe method to get IP from UNIX systems ? Regards.
Although a computer can have multiple network interfaces and different IPs, some of the interfaces can also be loopback or not running. To be "safe" you might even have to check names of the interface to see if you use the IP address from desired one.
Following method will give you a list of ip addresses from non-loopback, up and running interfaces.
public static List<InetAddress> getIPAddress() throws SocketException {
List<InetAddress> ipAddresses = new ArrayList<InetAddress>();
Enumeration e;
e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e.nextElement();
if (ni.isLoopback() || !ni.isUp()) continue;
for (Enumeration e2 = ni.getInetAddresses(); e2.hasMoreElements(); ) {
InetAddress ip = (InetAddress) e2.nextElement();
ipAddresses.add(ip);
}
}
return ipAddresses;
}
Use the enumeration getNetworkInterfaces(); and cycle through them.
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while (eni.hasMoreElements()) {
NetworkInterface ni = eni.nextElement();
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if(!ia.isLinkLocalAddress()) {
System.out.println("Interface: " + ni.getName() + " IP: " + ia.getHostAddress());
}
}
}
On my linux box the isLinkLocalAddress() doesn't seem to work properly, as I get the 127.0.0.1 but that and the ipv6 version is easy to filter out manually.
Interface: wlan0 IP: 192.168.0.8
Interface: lo IP: 0:0:0:0:0:0:0:1%1
Interface: lo IP: 127.0.0.1
My machine is connected only on the wireless interface on 192.168.0.8
Check out the answers to this SO question:
How to enumerate IP addresses of all enabled NIC cards from Java?
I haven't tested it, but it seem to apply.