ip address in java - java

I've been asked to activate a certain piece of code if i was in my college. So I need to find the iP of where i am to match to my colleges iP. Was wonderng how to do this in java? I have already tried a loop back interface.

By using NetworkInterface.getNetworkInterfaces() and calling getInetAddresses() on each interface, you can see all IP addresses assigned to your computer. To check if you have an IP in your university's range, you could do something like this:
boolean onCampusNetwork() {
for(Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
NetworkInterface iface = ifaces.nextElement();
for(Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses.hasMoreElements;) {
InetAddress address = addresses.nextElement();
// return true if address is in the university's range; something like:
if(address.toString().startsWith("10.0")) {
return true;
}
}
}
// None of the IP addresses were in the university's range.
return false;
}
I haven't run this code, but it should do what you need.

Isn't there supposed to be some kind of protocol for automatic proxy discovery and configuration? Does your college have this already setup? Then it would be better if your code discovered the correct settings and had an option to override the settings.

There are all kinds of websites out there that will give you your public ip (or the public IP of your gateway, which I assume is what you want). You could tell the program to make an HTTP connection to one of those sites and get the page with the info on it. Since these sites have a very predictable format, the result would be very easy to parse with a regex or two. This only works if you have an internet connection though.
Alternatively, you could have the program try to connect to one of your college's intranet servers. If it can make the connection to a site that is not accessible to the outside world, it's on the LAN.

Related

getting only url from ip address in java

The following java code will convert an IP Address to its host.
InetAddress addr = InetAddress.getByName("31.13.78.13");
String host = addr.getHostName();
System.out.println(host);
Here host will be printed as "edge-star-shv-01-sit4.facebook.com". The first portion may be the address of a data center of facebook. I only want the "facebook.com" portion. I could not find any built in method in InetAddress library that can sort this out. I can solve the problem using substring method but this is not a good way because I want a generalized approach. Is there any way where I can get "facebook.com" instead of "edge-star-shv-01-sit4.facebook.com" by taking "31.13.78.13" as input?
You can't!
I run multiple websites on one IP adress. So if you would use a script as you discribe it here, what should it return?
The only thing is to get the hostname of the server with the selected IP, this can contain the website name , as in your case, but it doesn't have to. Imagine a server with hostname "example.com" and IP 1.1.1.1, or whatever, on this machine a website in running with url "stackoverflow.com" then you expect when tracing the IP adress to get "stackoverflow.com" but in fact you would get "example.com"

Trying to get InetAddress.getLocalHost.getHostAddress (Java/Scala) to return external IP

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
}

How to figure out an IPv6 address (by name) of a host in my LAN

I have two computers plugged in the same router of a network which I know supports IPv6. Let's call them "PC-A" and "PC-B
I want "PC-A" to figure out "PC-B"s IPv6 address and vice-versa
The first thing I do is
setSystem.setProperty("java.net.preferIPv6Addresses", "true");
If I then say
InetAddress IPAddress = InetAddress.getLocalHost();
I can get my own address which will be in IpV6 format
However, neither of the following two statements gives me "PC-B"s IPv6 address:
Inet6Address IPAddress6 = (Inet6Address)InetAddress.getByName("PC-B");
InetAddress IPAddress = InetAddress.getByName("PC-B");
I also tried to import
import com.lavantech.net.dns.SimpleDNSLookup;
import com.lavantech.net.dns.DNSLookup
The first one I am using as:
SimpleDNSLookup d = new SimpleDNSLookup();
System.out.println(d.getInet6Address("PC-B"));
and the second one as:
DNSLookup dnsLookup = new DNSLookup("PC-B", DNSLookup.QTYPE_AAAA, DNSLookup.QCLASS_IN, 3000, null);
// Get all Address Records.
ResourceRecord[] ansRecords = dnsLookup.getAAAARecords();
System.out.println(ansRecords[0]);
none of which works.
I also tried to use the following
import org.xbill.DNS.*;
int type = Type.AAAA;
Name name = Name.fromString("PC-B");
Lookup lookup = new Lookup(name, type);
lookup.run();
int result = lookup.getResult();
Record[] answers = lookup.getAnswers();
System.out.println(answers[0]);
// (where, for brevity, i am skipping the parts where I check whether result == Lookup.SUCCESSFUL
Note that if I substitute "PC-B" for, say, "ipv6.google.com" I get all the desired results!
Also note that if I just use InetAddress and Type_A wherever applicable in the above approaches, my program returns "PC-B"s IPv4 address without problem.
What am I missing?
Any help is greatly appreciated!
Your question is -unfortunately- a yet unsolved network problem dealing with host discovery on a local subnet (regardless if that subnet has a router or not).
Your desired output is clearly an IPv6 address, but it is unclear what exactly your input is.
Let's focus on PC-B. How exactly do you identify PC-B? It clear that you call it "PC-B", but that name should be configured somewhere before your PC know that that's its name. Where exactly is that configured? Is that the hostname you set on PC-B itself, or is there a domain name server (DNS) where you have given that name? If it is the name in the DNS system, you can indeed query the DNS system for the AAAA record to get the IPv6 address, but you need the fully qualified domain name (FQDN). E.g. "PC-B.yourdomain.com" rather than just "PC-B".
If you know the MAC address of PC-B, you can use the neighbour discovery protocol (NDP) to find out the IP address of PC-B.
There are network protocols that allow PC-A and PC-B to announce their names themselves, once you configured them on the local machines. Such protocols are called "service discovery" protocols, and your options here are (1) multicast DNS (mDNS) and possibly DNS service discovery (DNS-SD) on top of that; or (2) Simple Service Discovery Protocol (SSDP) in UPnP on the other hand. The advantage is that some operating systems already implement this. E.g. if PC-B is a Mac OS X host, all you need to do is query DNS for "pc-b.local" to get the answer. Unfortunately, while implementations of mDNS exist for Linux (Avahi) and Windows (Bonjour), they're not installed by default. A third alternative is to write your own host discovery protocol, and have your hosts run that protocol.
Considerations are which platforms you want to support, if installing third-party software is an option, if the discovery needs to be secure (the above options are not, look into Secure Neighbour Discovery -SEND- if this is a concern), and what input you have in the first place (the hostname "PC-B", or the type of service that runs on PC-B, e.g. _http._tcp for a webserver).

Why isn't Java's InetAddress class resolving ipv6 addresses to their FQDN?

I'm trying to write a simple program using Java that, given an IP in either version 4 or 6 format, will return its FQDN. The following code works fine when given an ipv4 address, but will only return the given address when an ipv6 address is entered.
InetAddress inet;
try { inet = InetAddress.getByName(theIpAddress); }
catch(UnknownHostException e) { System.out.println("Unknown Host"); return; }
System.out.println(inet.getHostAddress(););
System.out.println(inet.getHostName(););
Whenever I enter an ipv6 getHostName() will only return the same ipv6, even when I know that the ipv6 will resolve to a FQDN. Also, if I enter an ipv6 host name, such as ipv6.google.com, in place of theIpAddress, the exception will occur.
I'm new to this stuff so would appreciate any assistance. Thanks.
The problem was actually the version of Java I was running. Updating Java to 1.6.23, from 1.6.21, allowed ipv6s to resolve to their FQDN.
I've done a quick investigation of what's going on with hostname <-> ipv6 resolution in java 8, Windows 7.
Looks like 'default' NameService does not work with ipv6 at all!
But! Java comes with another, JNDI based NameService implementation called 'dns,sun'.
So, if you enable it using either
-Dsun.net.spi.nameservice.provider.1=dns,sun
or
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
you will get bidirectional ip <-> hostname resolution for v4 and v6 addresses like this
InetAddress.getAllByName(...)
address.getHostName()
More info about java ipv6 you can find here http://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/
Try inet.getCanonicalHostName(); which "Gets the fully qualified domain name for this IP address."
If you construct the InetAddress using InetAddress.getByName(), getHostName() will return what you constructed it with. getCanonicalHostName() forces a reverse name lookup.
Using java.net.InetAddress it is not possible to have ipv6 and ipv4 name resolution etc. The bunch of static methods like getByName etc delegate the lookup to instance of Inet4(or 6)AddressImpl that does
public native InetAddress[] lookupAllHostAddr(String hostname) throws UnknownHostException;
Now the fun is a) all these are private/package local so there is not way to inject the impl classes to the InetAddress class b) Inet4(or 6)AddressImpl classes are themselves package local . So there is no way to say , do a ipv4 or ipv6 lookup/name resolution on the fly. I do not get the way all extension points were blocked for these classes making them of really very limited use and flexibility.
The real black-magic happens here , where InetAddress class statically initializes the impls, on what does outcome of method isIPv6Supported() dependent ?? My Linux setup supports ipv6 , i can do dns lookups for ipv6 hostnames like ipv6.google.com.
Will appreciate if anybody can point me to the direction of a good net library in java for ipv4/v6 utilities like lookup etc.
class InetAddressImplFactory {
static InetAddressImpl create() {
Object o;
if (isIPv6Supported()) {
o = InetAddress.loadImpl("Inet6AddressImpl");
} else {
o = InetAddress.loadImpl("Inet4AddressImpl");
}
return (InetAddressImpl)o;
}
static native boolean isIPv6Supported();
}

After Port Forwarding, how to get my external IP in Java?

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.

Categories

Resources