I'm trying to make a wireless audio connection between two android devices. So I found AudioStream class, and I have the partial code like this:
public String getMobileIP() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress .getHostAddress().toString();
return ipaddress;
}
}
}
} catch (SocketException ex) {
Log.e("tag", "Exception in Get IP Address: " + ex.toString());
}
return null;
}
public void Connect()
{
String ipaa=getMobileIP();
InetAddress local = InetAddress.getByName(ipaa);
AudioStream audioStream = new AudioStream(local); <<----- exception
...
...
}
I want both phones to connect by voice using the AudioStream so that both people can talk and hear each other like a walkie-talkie.
I decide to use the mobile network IP address of the phone (Not the WiFi address), but when I do that the above code crashes when I use that to create the AudioStream.
I want the users to be able to talk to each other weather they are on WiFi or not (using mobile network).
Does anybody know how to fix this?
Documentation says exception occurs if the address cannot be bound or a problem occurs during binding. I think you could accomplish through Wi-fi because you were in the same network. However, when using mobile data IPs of ISPs (Internet Service Providers) might not see each other (it depends on ISP). Hence connection cannot be established.
Obvious solution is that your voice should go through some server where both clients can see it.
Related
I want detect network is wifi or ethernet at mac and windows.
NetworkInterface.getNetworkInterfaces()
This code can get the name of the networkinterface,but I don't know the network is wifi or ethernet.Please help me....
(If I understand your question) You may be able to try something like looking at the Local Address of different Network Interfaces. If a wlan has a private IP Address, you could assume it's connected to the network using wireless technology. If an eth has a private IP Address, you could assume it's connected to the network via ethernet. I don't know if this is 100% effective. This is not my area.
import java.net.*;
import java.util.*;
public class Main {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) {
try {
NetworkInterface nif = netint;
if(nif==null){
System.err.println("Error getting the Network Interface");
return;
}
Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
InetSocketAddress inetAddr= new InetSocketAddress(nifAddresses.nextElement(),0);
System.out.println("Interface: " + nif.getName());
DatagramSocket socket = new DatagramSocket(inetAddr);
System.out.println(socket.getLocalAddress());
System.out.println("");
} catch (SocketException ex) {
System.out.println(ex.toString());
}
catch(NoSuchElementException ex)
{
//System.out.println(ex.toString());
}
}
}
Output
Interface: lo
/127.0.0.1
Interface: eth4 //Number changed!
/131.555.555.55
Looking at this output, I would assume that eth4 has a network connection.
You cannot know, you're not supposed to need to know, in application code. At the level Java applications run, there is no difference between networks, all you have is a TCP/IP stack and you can't determine based on that what kind of network you're working on.
You'd have to write something in native code that interfaces with low level operating system functionality (and don't ask me what or how, it's dependent on operating system obviously) to get that information.
Im new for android, I want to get country name and country code using ip address. Please anyone guide me.
Below code for getting IP:
public String getLocalIpAddress() {
WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(context.WIFI_SERVICE);
if(wifiMgr.isWifiEnabled()) {
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String wifiIpAddress = String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
return wifiIpAddress;
}else{
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();
Log.i("","111 inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
//the condition after && is missing in your snippet, checking instance of inetAddress
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
Log.i("","111 return inetAddress.getHostAddress(): "+inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
return null;
}
I dont know how to get country code and name using IP address.
Thanks in advance!
1.) query your public ip-address:
public static String getPublicIP() throws IOException
{
Document doc = Jsoup.connect("http://www.checkip.org").get();
return doc.getElementById("yourip").select("h1").first().select("span").text();
}
2.) Then query your country code/name: (by using the method above)
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://ipinfo.io/"+getPublicIP());
HttpResponse response;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I hope this helps.
You may use this perfect guide: http://www.mkyong.com/java/java-find-location-using-ip-address/
//ip address something like that 192.168.0.1
public String getCountryFromIP(String ipAddress) {
File file = new File("resources/GeoLiteCity.dat");
LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
Location locationServices = lookup.getLocation(ipAddress);
return locationServices.countryName;
}
There's a better way than using third-party APIs and the frequently outdated GeoLiteCity database.
Check the ip2asn2cc library.
This library uses official databases provided by all Regional Internet Registries, which are frequently updated.
I was using APIs for this purpose in the past, and my service was hitting API rate limits very frequently. IMHO, ip2asn2cc provides more flexibility and cuts out external dependencies out of applications.
First you should get external IP address of the device, and then use some web API like this to get country code and name.
In one of my application I have same requirement to get user location based on ip address, as in android phone we can not get the external IP address. So we implement it at our server side by implementing web service. Through our web service we were able to get the user external ip address and then we used Maxmind API to get user country code and name. Maxmind Api's are paid but easy to implement.
I found some examples for setting up a multicast socket server (receiving) in Android and I'm trying to add that to my project. My constructor code looks like this:
try
{
this.socket = new MulticastSocket (PORT);
socket.joinGroup (InetAddress.getByName (MULTICAST_ADDRESS));
}
catch (Exception ex)
{
Log.e (TAG, "Start up error: " + ex.getMessage());
ex.printStackTrace();
this.running = false;
}
However, for reasons I don't understand, every time the joinGroup() line is executed an exception is thrown. Strangely, the printStackTrace() line doesn't give me anything, but the Log.e() business gives me the following:
Multicast Server: Start up error: setsockopt failed: ENODEV (No such device)
I have added the necessary permissions to my code (CHANGE_WIFI_MULTICAST_STATE, ACCESS_WIFI_STATE, & INTERNET), and I have acquired a Multicast lock as well.
Any suggestions at what's missing here?
By a round-about-path, this question became the same as mine:
http://stackoverflow.com/questions/8180275/multicast-no-such-device
And the answer turns out to be that I needed to specify the interface, since my fancy Panasonic Android tablet has more than one:
try
{
NetworkInterface eth0 = null;
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements())
{
eth0 = enumeration.nextElement();
if ("eth0".equalsIgnoreCase (eth0.getName()))
{
break;
}
}
this.socket = new MulticastSocket (PORT);
socket.setSoTimeout (60000);
socket.joinGroup (new InetSocketAddress (MULTICAST_ADDRESS, PORT), eth0);
}
catch (Exception ex)
{
...
This question already has answers here:
Getting the IP address of the current machine using Java
(19 answers)
Closed 8 years ago.
In my application I have written to find IP Address of user.
HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");
HttpServletRequest.getLocalAddr();
And getting the server ips can be done so:
Inet4Address.getLocalHost().getHostAddress();
So, If the user already logged in from one ip address, how to restrict his login from another ip address?
Try Following code:
Inet4Address address=(Inet4Address) Inet4Address.getLocalHost();
System.out.println(address.getHostAddress());
Inet4Address comes from java.net.Inet4Address;
Best way to find host address in LAN can be done as follows:
System.out.println(InetAddress.getByName("anyhostname").getHostAddress());
Try this, it will enumerate all the interface's address of your local machine.
try {
Enumeration<NetworkInterface> interfaceEnumeration =
NetworkInterface.getNetworkInterfaces();
while (interfaceEnumeration.hasMoreElements()) {
Enumeration<InetAddress> inetAddressEnumeration =
interfaceEnumeration.nextElement().getInetAddresses();
while (inetAddressEnumeration.hasMoreElements()) {
System.out.println(inetAddressEnumeration.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
But the following method is not reliable, in my testing environment, it always return the loop back interface address.
try {
InetAddress inetAddress[] = InetAddress.getAllByName("localhost");
for (InetAddress address : inetAddress) {
System.out.println(address.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
I made one android application that needs to connect one local database provided by wamp server. First using the android virtual device (AVD) my IP to connect the server first time used to be: 10.0.2.2. My AVD was connecting fine, but when I tried to connect direct on my device he wasn't finding the local server with this 10.0.2.2 IP. At this point I've changed IP to 192.168.1.5 which was my LAN cable IP, both device and AVD were running without problems... but sometimes I need to change my connection to wifi, which changes the IP..also, I realized that fix one IP in my source code will be a problem to release the android app, since other people will have other LAN IP address.
To solve this problem, I've started to look for a solution, such as acquire the LAN IP dynamically. For this purpose I built this Java application as test:
public class test {
public static void main(String[] args) throws Exception
{
String roundHost = null;
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
if (addr.isSiteLocalAddress()){
String pureHost = addr.getByName(addr.getHostName()).toString();
roundHost = addr.getHostAddress();
pureHost = pureHost.substring(addr.getHostName().length()+1);
if(!roundHost.equals(pureHost))
break;
}
}
}
System.out.println(roundHost);
}
}
As output, this java application gives me my correct LAN wifi IP or even my LAN cable IP which is 192.168.1.3 or 192.168.1.7. From here I made one "IPParser" to use on my android app:
public class IPParser {
String pureHost, roundHost = null;
public IPParser() throws UnknownHostException{
Enumeration<NetworkInterface> n = null;
try {
n = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
e1.printStackTrace();
}
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
if (addr.isSiteLocalAddress()){
pureHost = addr.getByName(addr.getHostName()).toString();
roundHost = addr.getHostAddress();
pureHost = pureHost.substring(addr.getHostName().length()+1);
if(!roundHost.equals(pureHost))
break;
}
}
}
}
public String returnIp() {
return roundHost;
}
}
As you can see it's pretty similar; the difference is just some structural changes to adapt the needed syntax. And now comes the real problem: When I try to run this parser inside my AVD, my ip is 10.0.2.15 and running directly in my device the ip return is 192.168.1.6 - Obviously the android app is crashing because it can't find the local server to connect.
My IP config information:
I'm not an expert in network, so I ask, take it easy and if I said something technically wrong or adjacents please edit and correct me..finally I ask:
Why this is happening and what's possible to do to solve this problem?
The IPs you mention (10.0.2.2 and 192.168.1.5) are from two different networks, which makes sense since the documentation states that:
Each instance of the emulator runs behind a virtual router/firewall
service that isolates it from your development machine's network
interfaces and settings and from the internet. An emulated device can
not see your development machine or other emulator instances on the
network. Instead, it sees only that it is connected through Ethernet
to a router/firewall.
The virtual router for each instance manages the 10.0.2/24 network
address space — all addresses managed by the router are in the form of
10.0.2., where is a number. Addresses within this space are pre-allocated by the emulator/router as follows:
What this means is that when using the AVD there is a virtual network that is created which the device and the computer are part of. In your case your local machine takes the address 10.0.2.2 in this virtual network and the AVD 10.0.2.15. But when you connect directly through your device, the computer's IP (as well as the device's) is in the LAN's address space (i.e. 192.168.1.5 and 192.168.1.6).
The code you posted resolves the IP address of the host, but if you want the device to resolve automatically the server's IP address and you can guarantee they will always be both connected to the same LAN, then you can use multicast UDP messages (I didn't find a really good source but you can start here, here and here). This type of communication sends a UDP datagram to the network to a specific multicast IP address and port, to which other devices in the network are listening. I've used this scheme in an Android application that needed to find a computer in the network so I know for a fact that it works. I can share some code if you need to.
EDIT
The following snippets of code are the ones that implement the search of computers in the network. The Android application this was used in could control the mouse and keyboard of any computer in the network that had the server application running.
Android Client
public void findComputers(View v) {
try {
int port = 4444;
String multicastAddr = "224.168.1.0";
DatagramSocket socket = new DatagramSocket(port);
socket.setSoTimeout(300);
InetAddress group = InetAddress
.getByName(multicastAddr);
DatagramPacket packet = new DatagramPacket(new byte[] { 1 }, 1,
group, port);
socket.send(packet);
// Give time to the servers to respond
Thread.sleep(100);
while (true) {
try {
// Listen for the servers responses
byte[] buffer = new byte[256];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String data = new String(packet.getData());
// Information sent from servers include the host's name
// and IP addres separated by a semicolon.
String[] parts = data.split(";");
// Add a server to the result list.
Computer computer = new Computer(parts[1].trim(),
parts[0].trim());
this.computers.put(computer.getName(), computer);
} catch (InterruptedIOException ex) {
break;
}
}
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
String output = "No computers found.";
if (this.computers.size() > 0) {
output = this.computers.size() + " computer(s) found.";
this.fillComputers();
}
Toast.makeText(this, output, Toast.LENGTH_SHORT).show();
}
Server
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/**
* Receives UDP broadcast packets in the default port requesting for server name
* and IP, broadcasting the information in return.
*
* #author jfacorro
*
*/
public class NameResolverService extends Thread {
private InetAddress localAddress = null;
private byte[] localAddressData = null;
private MulticastSocket socket = null;
private boolean exit = false;
public NameResolverService() {
}
public void exit() {
this.exit = true;
this.socket.close();
}
#Override
public void run() {
try {
int port = 4444;
String multicastAddr = "224.168.1.0";
// Get current address
this.localAddress = InetAddress.getLocalHost();
this.socket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(multicastAddr);
this.socket.joinGroup(group);
this.localAddressData = (this.localAddress.getHostAddress() + ";" + this.localAddress
.getHostName()).getBytes();
} catch (IOException ex) {
this.notified.notified(ex.getMessage());
ex.printStackTrace();
}
while (!this.exit) {
try {
byte[] buffer = new byte[1];
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(this.localAddressData,
this.localAddressData.length, address, port);
socket.send(packet);
} catch (IOException e) {
if(!this.exit)
e.printStackTrace();
}
}
this.socket.close();
}
}