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.
Related
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.
I'm trying to write a packet capturing java program using the jnetpcap library. But I wonder if I can get the PID from a given port? In my case, I'm trying to use Sigar API to get the PID (method name is getProcPort(protocol, port)).
PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<String>(){
public void nextPacket(PcapPacket packet, String user) {
Tcp tcp = new Tcp();
Ip4 ip = new Ip4();
String protocol;
long port;
if(packet.hasHeader(ip)&&packet.hasHeader(tcp)){
protocol = tcp.getName();
port = tcp.source();
try {
//but the following line will cause an error
long pid = sigar.getProcPort("tcp", Long.toString(port));
System.out.println("pid : " + pid);
} catch (SigarException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(filtering==false){
printPacketResult(packet, tcp, ip, port, protocol);
}else if(filtering==true){
filteredPrintPacketResult(packet, tcp, ip, port, protocol);
}
}
}
};
and the error I get is:
org.hyperic.sigar.SigarNotImplementedException: This method has not
been implemented on this platform at
org.hyperic.sigar.SigarNotImplementedException.(SigarNotImplementedException.java:28)
at org.hyperic.sigar.Sigar.getProcPort(Native Method) at
org.hyperic.sigar.Sigar.getProcPort(Sigar.java:632) at
networkInfo.PackageCapture$1.nextPacket(PackageCapture.java:84) at
networkInfo.PackageCapture$1.nextPacket(PackageCapture.java:1) at
org.jnetpcap.Pcap.loop(Native Method) at
org.jnetpcap.Pcap.loop(Unknown Source) at
networkInfo.PackageCapture.startNet(PackageCapture.java:111) at
networkInfo.FilterChoice.choice(FilterChoice.java:27) at
networkInfo.Main.main(Main.java:6)
Is it a possible? If you have some information, please give me some hint.
I have a serious issue regarding the REST API of Mailjet as used with the recommended v3 library.
When I try to UPDATE I am able to do so for the first time without errors, but when I try to do so again, I got NullPointerException. In spite of that, it does update the stat in the Mailjet Server part.
Also the HTTP Response I get is HTTP/1.1 500 Internal Server Error
Code used:
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, **myUniqueID**).property(UserProperty.USERNAME, propertyValue).execute();
Any thoughts would be more than welcome.
Ok after the comment, here is the function:
#Path("/userUpdate/{propertyName}/{propertyValue}")
#GET
public Response userUpdate(#PathParam("propertyName") String propertyName, #PathParam("propertyValue") String propertyValue) throws ClientProtocolException, IOException{
MailJetApiClient cl=null;
User thisUser=null;
Response resp=null;
StringEntity stringEntity = null;
try {
cl = MailjetUsersRest.createClient();
} catch (MailJetClientConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
thisUser=cl.createCall(User.Get).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).execute();
} catch (MailJetApiCallException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try {
cl = MailjetUsersRest.createClient();
switch(propertyName){
case "Username":
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).property(UserProperty.USERNAME, propertyValue).execute();
resp = Response.status(200).entity(thisUser).build();
break;
default:
System.out.println("Invalid propertyName.");
break;
}
} catch (MailJetClientConfigurationException | MailJetApiCallException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
First of all, thank you for using Mailjet!
After some testing, I was unable to reproduce your issue. You will find below the code I used.
However I strongly suggest that you open a ticket with our support here.
A working code
Please note that it is unnecessary and considered bad practice to rebuild the client before each call.
// Build a Mailjet client config
MailJetClientConfiguration config;
config = new MailJetClientConfiguration()
.setBaseUrl("https://api.mailjet.com/v3/REST/")
.setDefaultApiKey(System.getenv("MJ_PROD_PUBLIC"))
.setDefaultSecretKey(System.getenv("MJ_PROD_PRIVATE"));
// Build a Mailjet client
MailJetApiClient client = config.buildClient();
// Your code (adapted to my environment, ie no 'Response' object
// and no client factory.)
User thisUser = null;
try
{
// Note that the 'L' in the 'identifiedBy' value fi is necessary
thisUser = client
.createCall(User.Get)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.execute();
}
catch (MailJetApiCallException e2)
{
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try
{
thisUser = client
.createCall(User.Update)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.property(UserProperty.USERNAME, "DevRel Team Mailjet")
.execute();
}
catch (MailJetApiCallException e)
{
e.printStackTrace();
}
Copy pasting the last bit (the update process) so that the update call is executed twice (without the same new username, of course) doesn't throw any error and certainly not a NullPointerException or a 500 HTTP error code.
And the username is changed accordingly.
So yeah, as written above, please contact our support here. This will allow us to better help you.
If this answer satisfies you, don't forget to accept & upvote it so that others going through similar issues can know this helped :-)
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();
}
}