so I have an app that is running and on startup, I would like to be able to Get the IP address and display it as a String. I have been using the code below.
String ipAddress = "";
try{
ipAddress = Inet4Address.getLocalHost().getHostAddress();
}
catch(Exception e){
ipAddress = "IP address Cant be used";
}
every time this is run it will return "IP address Cant be used" so it's throwing an error.
If you are looking to get your public facing IP check out this answer. In short you cannot get your public facing IP because the Network Address Transation does not happen in your Kernel, i.e you dont assign your IP to yourself rather it will be given to you thanks to NAT and DHCP. The following code makes a request to amazons's aws IP API, to retrieve your IP
public static String getIp() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I didn't find the right solution. The below code gives me local IP address (if I connected to Wifi, it gives IP address like 192.168.0.x), but I want public IP address (same as if I search in google " what is my IP ")
public static String getLocalIpAddress() {
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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
OR
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Can anyone help? Thanks!
Step #1: Create a Web service that returns the requester's IP address
Step #2: Call that Web service from your app.
A device does not know its public IP address (unless that device was seriously misconfigured).
You may use the WS https://api.whatismyip.com/ip.php from whatismyip.com : This would output only your IP address in the simple text. (No input required, output is optional)
You must be a Gold Level Member to access the API
Updated Answer
You can make use of the web service from ipify.org
Read through the documentation here
Use https://api.ipify.org/?format=json WS to get device public IP address. This would output your IP address in JSON format.
You should use ipify because:
You can use it without limit (even if you're doing millions of requests per minute).
It's always online and available, and its infrastructure is powered by Heroku, which means that regardless of whether the server running the API dies, or if there's an enormous tornado which destroys half of the east coast, ipify will still be running!
It works flawlessly with both IPv4 and IPv6 addresses, so no matter what sort of technology you're using, there won't be issues.
....................
....................
I found this simple solution:
public String getExternalIpAddress() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Remember that this must be run on a separate thread.
You can do this with a simple thread.
you need to create a function in Activity.class file, and need to request a url that will give your public IP in text form: "https://api.ipify.org/. Click to open.
Add this function call in your onCreate() function.
getPublicIP();
Add this function in your MainActivity.class.
private void getPublicIP() {
new Thread(new Runnable(){
public void run(){
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("https://api.ipify.org/"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
PermissionsActivity.this.runOnUiThread(new Runnable(){
public void run(){
try {
Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
Make a call to a server like https://whatismyipaddress.com or http://howtofindmyipaddress.com/.
If you have the page source then parse the ip address out.
There are other servers who only return your ip address. Not a whole html page as above two. But i forgot which one...
I'm writing an application that should scan a local area network for connected devices, and return the IP addresses of connected devices.
My scanner consists of "pinging" each IP within a range of IP addresses. This process of pining a range of IP addresses is time consuming.
Then I learned there is something called an ARP (address resolution protocol) cache on Windows machines which is basically a list of valid IP addresses, or IP addresses of connected devices.
So since Android isn't Windows, is there a way to access a similar table simply using an API or something?
Tl;Dr How can I query valid IP addresses on a network (not ping them) in Android
Best solution I came up with so far was to read the ARP file in the Android device at file path /proc/net/arp
Here's the main activity class for the app that displays the file content in a simple text view
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.textView);
// Get an array list of mac to IP address mapping
ArrayList<String> arpTableLines = getArpTableLines();
// Generate a string to display in the text view based on the mapping
String textViewText = getTextViewText(arpTableLines);
// Set the text view value
tv.setText(textViewText);
}
public ArrayList<String> getArpTableLines(){
ArrayList<String> lines = new ArrayList<>();
try{
String line = "";
BufferedReader localBufferdReader =
new BufferedReader(new FileReader(new File("/proc/net/arp")));
while ((line = localBufferdReader.readLine()) != null) {
String[] ipmac = line.split("[ ]+");
if (!ipmac[0].matches("IP")) {
String ip = ipmac[0];
String mac = ipmac[3];
lines.add(ip + " <~> " + mac);
}
}
}catch (FileNotFoundException ex){
Log.v("TAG",Log.getStackTraceString(ex));
} catch (IOException ex){
Log.v("TAG",Log.getStackTraceString(ex));
}
return lines;
}
public String getTextViewText(ArrayList<String> lines){
String result = "";
for(String line : lines) result += line + "\n";
return result;
}
}
Does anyone know if BT_MULTI works on Zebra? I'm using ZebraConnection class in my android application and connection with BT:printerAddress as parameter works but with BT_MULTI:printerAddress throws "Invalid connection type".
I'm trying to use BT_MULTI to connect multiple printers in one time, but if you have other ideas of how I can do that I'll be happy to hear them.
This is the code that throws the exception:
Connection connection;
try {
connection= ConnectionBuilder.build(getConnectionStringForSdk(printerBTAddress));
connection.open();
ZebraPrinter printerdemo = ZebraPrinterFactory.getInstance(connection);
} catch (ConnectionException e) {
System.out.println("Connection could not be opened"+e);
} catch (ZebraPrinterLanguageUnknownException e) {
System.out.println("Unable to create printer"+e);
}
private String getConnectionStringForSdk(String btAddress) {
String selectedPrefix="BT_MULTI:";
final String finalConnectionString = selectedPrefix + btAddress;
return finalConnectionString;
}
How to get 'current(actual) time' or 'network operator's time' programmatically if device time is changed ?
I'm trying to get current time through 'getLastKnownLocation' method of 'LocationManager' class. But it gives last location time, but I need current time.
Can anyone tell me a clue about the correct way to get actual time from internet ?
If possible without using any external library.
Thanks in advance.
According to this answer you can get the current time from an NTP server.
support.ntp.org library
Add to your dependency
String timeServer = "server 0.pool.ntp.org";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(timeServer);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getReturnTime();
System.out.println(returnTime)
You can use a rest full api provided by geo names http://www.geonames.org/login it will require lat and long for this purpose for example
http://api.geonames.org/timezoneJSON?lat=51.5034070&lng=-0.1275920&username=your_user_name
For Android:
Add to gradle app module:
compile 'commons-net:commons-net:3.3'
Add to your code:
...
String TAG = "YOUR_APP_TAG";
String TIME_SERVER = "0.europe.pool.ntp.org";
...
public void checkTimeServer() {
try {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long setverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
// store this somewhere and use to correct system time
long timeCorrection = System.currentTimeMillis()-setverTime;
} catch (Exception e) {
Log.v(TAG,"Time server error - "+e.getLocalizedMessage());
}
}
NOTE: timeInfo.getReturnTime() as mentioned in an earlier answer will get you local system time, if you need server time you must use timeInfo.getMessage().getTransmitTimeStamp().getTime().
Getting the time from the third-party servers is not reliable most of the times and some of them are paid services.
If you want to get the exact time and check with the phone whether it is correct or not, irrespective of the proper way, you can use the following simple trick to get the actual time.
private class GetActualTime extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result.append(line);
in.close();
}
else {
return "error on fetching";
}
return result.toString();
} catch (MalformedURLException e) {
return "malformed URL";
} catch (IOException e) {
return "io exception";
} finally {
if (urlConnection != null) {urlConnection.disconnect();
}
}
} catch (Exception e) { return "null"; }
}
#Override
protected void onPostExecute(String time) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
String times = mdformat.format(calendar.getTime());
try {
String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim();
Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();
}
catch(IndexOutOfBoundsException e){
Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
}
}
}
}
Call the class in the onCreate();
new GetActualTime().execute("https://www.google.com/search?q=time");
So this is actually getting the time from Google. This works pretty awesomely in my projects. In order to check whether the system time is wrong, you can use this trick. Instead of depending on the time servers, you can trust Google.
As it is more sensitive in checking, even a minute ahead or lag will catch the exception. You can customise the code if you want to handle that.
Try this :
System.currentTimeMillis();
I am developing shopping cart application in Android 2.1 . I want to print the order details ( customer details , cart details, order total) , when user submit the order . I want to use some WIFI printer for printing the data. Please help me with suitable examples ...
I assume you want to print on receipt-sized paper. If so, Star Micronics has an Android SDK with support for Wifi connections as well as USB and Bluetooth. Download it here: http://starmicronics.com/support/sdkdocumentation.aspx
If you're looking for a regular size printer, check out Google Cloud Print: https://developers.google.com/cloud-print/?hl=en
Create a Socket connection from ip address and port number.
String ip = "your printer ip address";
int port = port number;
private class printTCP extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
if (!ip.equals("")) {
if ((pref.getString(Const.PORT_CASH) != null) && (!pref.getString(Const.PORT_CASH).equals(""))) {
port = Integer.parseInt(pref.getString(Const.PORT_CASH));
try {
client = new Socket(ip, port);// ip address and port number of ur hardware device
String text = "Test Print";
byte[] bytes = text.getBytes(); //create a byte array
outputStream = client.getOutputStream();
outputStream.write(bytes, 0, bytes.length); //write file to the output stream byte by byte
outputStream.flush();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}