This question already has answers here:
Getting the IP address of the current machine using Java
(19 answers)
Closed 9 years ago.
What is the best way to get IP address in Java? I was trying getLocalHost(), but it returns my computer IP addrees. I want something like this.
Also I was trying to get IP by HTML from services like that, but I think it's not good idea.
The following uses Amazon web services and works for me.
import java.net.*;
import java.io.*;
public class IPTest{
public static void main(String args[]) throws Exception{
URL whatismyip = new URL("http://checkip.amazonaws.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println("My IP address:"+ip);
}
}
You want to get your internet (someone will call public, I don't totally agree on that term) ip address. Basically you have two options, or call an external service (it does not need to be a site like that, it can be a STUN, or anything made for that), or you can get it from your modem/router/NAT.
You could use UPnP if enabled in the device, this is a good approach.
Other option is instead of trying to parse or get the results from an external service,
you get it from your device web page, some devices even not need admin rights to get that information, so you only need to parse the page for the information.
Most of the answers just say you to use an external service, like you said its not a good idea. In my opniation its not the best one, because you be dependent on an external service provider. If it changes anything you need to change too, as if they get the service broken.
So, if you can implement in your own LAN its better, just not easier.
Related
I'm trying to create an OSGi bundle that'd be installed on a eurotech gateway (reliagate 10 05).
This bundle would essentially connect the gateway to a BLE device.
To do so, I use a framework provided by eurotech called Everyware™ Software Framework (ESF) that adds up an extra layer on top of the kura v1.2.0 framework.
The catch is, the BLE device only accepts random static address type.
I managed to connect the gateway manually to the BLE device using the following commands in console:
hcitool -i hci0 lecc --random <BD_ADDR>
then
gatttool -i hci0 -b <BD_ADDR> --interactive
This works fine. The hard part is when I try to do the same thing in code using the ESF/kura framework.
Here's a snippet from a sample I use that I found on this page
public boolean connect(String adapterName) {
this.bluetoothGatt = this.device.getBluetoothGatt();
boolean connected = false;
try {
connected = this.bluetoothGatt.connect(adapterName);
} catch (KuraException e) {
logger.error(e.toString());
}
if (connected) {
this.bluetoothGatt.setBluetoothLeNotificationListener(this);
this.isConnected = true;
return true;
} else {
// If connect command is not executed, close gatttool
this.bluetoothGatt.disconnect();
this.isConnected = false;
return false;
}
}
Here is a list of some objects that the sample uses to scan and establish a connection:
org.eclipse.kura.bluetooth.BluetoothAdapter;
org.eclipse.kura.bluetooth.BluetoothDevice;
org.eclipse.kura.bluetooth.BluetoothGattSecurityLevel;
org.eclipse.kura.bluetooth.BluetoothGattService;
org.eclipse.kura.bluetooth.BluetoothLeScanListener;
org.eclipse.kura.bluetooth.BluetoothService;
org.eclipse.kura.bluetooth.BluetoothDevice;
org.eclipse.kura.bluetooth.BluetoothGatt;
org.eclipse.kura.bluetooth.BluetoothGattCharacteristic;
org.eclipse.kura.bluetooth.BluetoothLeNotificationListener;
So I searched through the api doc but didn't find anything.
Though, one interesting SO post mentions a command code to send to the device.
I found a method in kura framework that might help.
Here's the signature:
void ExecuteCmd(java.lang.String ogf, java.lang.String ocf, java.lang.String parameter)
but I couldn't figure out the OpCode Group Field (ogf) associated to the OpCode Command Field(ocf) in any documentation (I skimmed the ~2300 pages of the Bluetooth 4.0 core spec). If anyone knows where to search... :)
In the end, the question is: is there a way to set the address type to random (as with the hcitool command) with the kura framework ?
Or am I totally misleaded ? :/
Anyway, I'm really new to the kura and ble ecosystems so, sorry if it looks like an obvious thing to do but I feel like I'm running out of inspiration and could totally use a hand!
PS: Congrats if you made it to the end!
Haha lol. Kura seems to just start a gatttool process, send commands in text, and parse the output as its interface...
Here is where it is stated, using the address as parameter: https://github.com/eclipse/kura/blob/0339ac787f90debdfc270c1dee0c16de16ea6f7e/kura/org.eclipse.kura.linux.bluetooth/src/main/java/org/eclipse/kura/linux/bluetooth/util/BluetoothUtil.java#L319. Unfortunately the Kura developers seem to have missed that there is something called Random Address in the BLE standard and I don't see how that could be worked around using the current API.
Okay so for those who find themselves in my position in the future, I just received an answer from the Eurotech support team.
Dear Mr. Carneiro,
[...]
Regarding the random BD_ADDR, this is a configuration of the BLE device.
So, your BLE device is advertising an address of type random, not public, and you should specify the address type on the connection string, as you already did.
Unfortunately, current Kura Bluetooth API doesn't provide a way to specify the type of address into the connection string. We are developing a new set of APIs for BLE that will be available on preview on the next Kura/ESF release, but the Reliagate 10-05 will not support these yet.
I have a need to create a http or https URL object from an IPv4 address (String or InetAddress objects - either one is ok) in Java. I have been at this for 10 hours now.
Attempts that hit a wall described below:
Attempt #1: I tried to make the URL by assembling a string, and then feeding it to a URL constructor.
Textbook states that a URL can be "protocol://host", with host being either a host name or IP address. but creating a URL like this: URL a = new URL("http://151.101.65.69"); and opening a stream to this URL (a) gives a HTTP error 500 (Internal Server Error - An unexpected condition occurred that the server does not know how to handle).
What get me fuming is that URL a = new URL("http://stackoverflow.com"); works.
At this point I am stuck. I have no Idea what to change, or how to move forward.
Attempt #2: I tried to do a reverse lookup on the IP address using "getHostName()" method in the InetAddress class.
this should return the host name by doing a reverse DNS lookup. Yet, I keep trying it for 151.101.65.69 (stackoverflow web server IP address), and the look up fails. By fails I mean the IP address is returned as string rather than the host name as a string. I read the Oracle docs http://docs.oracle.com/javase/1.5.0/docs/api/java/net/InetAddress.html#getHostName(), but I don't understand how to overcome the "security manager" the document mentions (or if it is indeed the reason the reverse lookup fails).
I also tried "getCannonicalHostName()", but that didn't fly either.
I am trying to figure out how to open a website using the IP address. It looks like my browser is running into the same issue as my code. I read up on How to access site through IP address when website is on a shared host? but I do not have any user names, as I want to be able to open any website that a user has an IP address for. Adding a port (such as 80) does not seem to work; neither does leaving the user name blank or using a generic 'user' or 'guest'.
I need is to create a URL object from an IPv4 String or InetAddress object, and I am stuck. I understand that a knowledgeable programmer such as you, may say that making URLs from IP addresses is not what IP addresses are for, or point out that I am not including a file portion of the URL, but that is not the problem at this moment. Could you please help me with my core challenge?
The answer provided by D.B. is good. I had very similar code; but you will find that this code will not work every time. There are IPv4 addresses you pass to the code offered D.B.'s answer which will not be able to open a URL stream (for example the IP address for stackoverflow). I thought the problem was my coding, and that is what I was hoping to get help with on stackoverflow. But I now realize the problem was my lack of understanding when asking this question. What I now understand, is that having an IPv4 address is not sufficient to open every website on the web. Anytime a server hosts multiple websites, the IP address can be used to connect to the server, but not to simultaneously identify the website we want to open/access. This gentleman explains this quite well: http://ask-leo.com/why_doesnt_accessing_a_site_by_its_ip_address_work.html
#D.B. thanks for taking the time to help. Much appreciated!
The following code works for me.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class InetAddressMain {
public static void main(String[] args) {
try {
InetAddress addr = InetAddress.getByName("172.217.4.110");
URL url = new URL("http://"+addr.getHostAddress());
InputStream is = url.openStream();
InputStreamReader isReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isReader);
String line;
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." ... [output shortened for readability]
So I'm having a problem with using InetAddress.getLocalHost.getHostAddress to get the external IP address of a given machine.
I'm actually doing this in Scala in a sense - the configuration file for Akka Remote Actors default uses InetAddress.getLocalHost.getHostAddress to get the IP address of the machine, which is what I want since I will be deploying the actors on several machines. However, it seems to be returning 127.0.0.1 instead of the external IP address I want (since the remote actors need to communicate back and forth across the netwrok).
The problem is that I can't use any of the methods I've found on Google to circumvent this since they all seem to involve adjusting the code itself, whereas here I don't really have any code to adjust, the DSL just automatically uses InetAddress.getLocalHost.getHostAddress.
I've read on a few threads from a Google search that you can circumvent this by editing your host file or something? How do I do this?
Thanks!
-kstruct
You may want to use NetworkInterface class.
In particular, use static getNetworkInterfaces method to enumerate all available network interfaces.
Check your /etc/hosts file. It should map 'localhost' to 127.0.0.1 and your real hostname to your real IP address, or one of them :-| Some Linux distributions get this wrong apparently.
i got a partial solution if getLocalHost doesn't works.
this solution have the problem that you must to know the name of your network interface in order to match the real one. Maybe you can improve this code removing "virtual" devices and something else.
This is scala code, but java code is very similar
def returnInterfaceAddress() : InetAddress = {
var myInetAddress = InetAddress.getLocalHost
val interfaces : util.Enumeration[NetworkInterface] = NetworkInterface.getNetworkInterfaces()
while(interfaces.hasMoreElements){
val inter = interfaces.nextElement()
if(inter.getDisplayName() == "Realtek PCIe GBE Family Controller"){
myInetAddress = inter.getInetAddresses().nextElement()
}
}
myInetAddress
}
Please excuse my noobishness as I am teaching myself Java and don't know a lot.
I'm trying to make a multiplayer game that runs from Java applets, I have a server-side program working that will accept strings of text, but all my attempts to find code for applets have failed.
My best attempt looks like it works but I think fails to connect to the server, any ideas why? (localIP is my correct IP and works fine in other tests)
public void init()
{
try
{
socket = new Socket(localIP, 5555);
inStream = new DataInputStream(socket.getInputStream());
outStream = new PrintStream(socket.getOutputStream());
}
catch(Exception e)
{
never reached
}
}
I don't mind scrapping this if someone can tell me a better way to do it or any way at all.
a java applet can only connect to the server from which it was downloaded. if you are not loading the applet from localIP, then you will not be able to connect to it.
you may be able to get around this restriction by signing the applet.
Given that you are not using the Http Protocol, One assumes that the applet is loaded from another port other than 5555. If this is the case, the applet needs to be signed in order to do this functionality.
I set up a static IP and did port forwarding on my notebook, and now I have a static IP address, but it's relatively static, every time I re-start the machine, I get another address, and since I have a "static" IP I can now do Paypal IPN messaging. But how can I get this static IP from my Java program ? One way I can think of is to visit : http://portforward.com/ and on that page it tells me what my external IP is, so I can extract it with Java code, is there any other way that I can do in my Java code to get this info ?
The best solution is probably dynamic DNS. Essentially, you run a program on your computer (or router) that notifies a DNS server when your IP changes. Then, you can just tell PayPal the domain name.
There is a public service you can call with your script to retrieve your external IP address. Bear in mind they have changed the link location once. If you control your own server, you should probably write your own PHP script to simply return the address of the caller to the script.
http://www.whatismyip.com/faq/automation.asp - follow the developers link they provide
import java.net.*;
import java.io.*;
URL myExternalIP = new URL("PUT THE LINK HERE");
BufferedReader in = new BufferedReader(new InputStreamReader(
myExternalIP.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
Your own server script is a simple one-liner. Create a file called whatismyip.php and here's the content.
<? echo $_SERVER['REMOTE_ADDR']?>
I see three ways of doing this:
As you discovered, querying an external server what IP you're apparently connecting from. This is simple but you require such a service to be available and, usually, that no transparent proxy messes with your results.
IGD, a sub-protocol of UPnP can give you the result very easily if your port forwarding devices supports it (many do). Google "IGD JAVA" for libraries and samples.
Register for a dynamic DNS service and then lookup your own DNS name.
You can use the NetworkInterface class:
Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
while(ifcs.hasMoreElements()){
NetworkInterface ifc = ifcs.nextElement();
System.out.println("Adresses of: "+ifc.getDisplayName());
Enumeration<InetAddress> adresses = ifc.getInetAddresses();
while(adresses.hasMoreElements()){
System.out.println(adresses.nextElement().getHostAddress());
}
}
This snippet will show you all of the interfaces and the IPs bound to them. You will need to look through the list to find the appropriate interface (see also NetworkInterface.getByName(String name)) And then look at the addresses for that interface. Once you have found the appropriate InetAdress you can use that to get the string or byte representation.