import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class GetIP{
public static void main(String[] args) {
try
{
InetAddress addr1 = InetAddress.getLoopbackAddress();
InetAddress addr2 = InetAddress.getLocalHost();
System.out.println("Host name:"+addr1.getHostName());
System.out.println("IP:"+addr1.getHostAddress());
System.out.println("Host name:"+addr2.getHostName());
System.out.println("IP:"+addr2.getHostAddress());
}catch(UnknownHostException e) {e.printStackTrace(); }
}
}
The two methods above are able to get the IP addresses and host names of the local machine only. If you want to get the IP addresses of a remote machine (e.g. IP addresses of a web server), you will use the getByName method. This method accepts the host name of the remote machine. You will use the URL class to point to the remote host.
public static void getIPfromURL(String strurl){
try {
URL url=new URL(strurl);
InetAddress address = InetAddress.getByName(url.getHost());
System.out.println(address.getHostAddress());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
hello,
ReplyDeletefor the first codes i have
Host name:localhost
IP:127.0.0.1
Host name:samraa
IP:127.0.1.1
what is the differents between two IP , how i can get my external IP (externe)
thansk
The two IP addresses are bounded to the loop back interface. It is not a great difference between those IP addresses. You might want to read http://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution to get more information about this bug in Linux OS.
DeleteThe following code will list all IP addresses bounded to your local machine.
Enumeration Enet;
try {
Enet= NetworkInterface.getNetworkInterfaces();
while(Enet.hasMoreElements()){
NetworkInterface ni=(NetworkInterface) Enet.nextElement();
Enumeration< InetAddress> Einet = ni.getInetAddresses();
while(Einet.hasMoreElements()) {
InetAddress ia= (InetAddress) Einet.nextElement();
System.out.println(ia.getHostAddress());
}
}
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This design is incredible! You certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool! uwell nunchaku kit
ReplyDeleteHaving said that, I am sorry, because I do not subscribe to your whole suggestion, all be it refreshing none the less. It seems to me that your opinions are generally not totally validated and in reality you are your self not really totally confident of the point. In any case I did take pleasure in reading it.wedding photography
ReplyDelete