Reputation: 13299
I'm writing a simple networking app. I need to know the real IP of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, I don't know if it is the same on windows). How to do it?
Upvotes: 56
Views: 93671
Reputation: 11
Get the ip address of the current box matching a pattern:
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
String ipPattern = "(192.1.200.)(\\d){1,3}"; //your organization pattern
try{
Enumeration en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) en.nextElement();
Enumeration ee = ni.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress ia = (InetAddress) ee.nextElement();
String ip = ia.getHostAddress();
System.out.println("ip: '" + ip + "'\n");
boolean matched = Pattern.matches(ipPattern, ip);
if (matched) {
System.out.println("matched\n");
}
}
}
}
catch(Exception e){ }
Result:
ip: 'fe80:0:0:0:510a:528b:7204:39d0%enp0s25'
ip: '192.1.200.3'
matched
ip: '0:0:0:0:0:0:0:1%lo'
ip: '127.0.0.1'
Upvotes: 1
Reputation: 1658
I wrote this code:
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
private String[] getHostAddresses() {
Set<String> HostAddresses = new HashSet<>();
try {
for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (!ni.isLoopback() && ni.isUp() && ni.getHardwareAddress() != null) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
if (ia.getBroadcast() != null) { //If limited to IPV4
HostAddresses.add(ia.getAddress().getHostAddress());
}
}
}
}
} catch (SocketException e) { }
return HostAddresses.toArray(new String[0]);
}
Check it!
For me:
Upvotes: 5
Reputation: 1919
Instead of using InetAddress.getHostAddress(), I call the getHost4Address routine that I wrote to get the first non-loopback address...
/**
* Returns this host's non-loopback IPv4 addresses.
*
* @return
* @throws SocketException
*/
private static List<Inet4Address> getInet4Addresses() throws SocketException {
List<Inet4Address> ret = new ArrayList<Inet4Address>();
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
ret.add((Inet4Address)inetAddress);
}
}
}
return ret;
}
/**
* Returns this host's first non-loopback IPv4 address string in textual
* representation.
*
* @return
* @throws SocketException
*/
private static String getHost4Address() throws SocketException {
List<Inet4Address> inet4 = getInet4Addresses();
return !inet4.isEmpty()
? inet4.get(0).getHostAddress()
: null;
}
Upvotes: 2
Reputation: 36115
As the machine might have multiple addresses, it's hard to determine which one is the one for you. Normally, you want the system to assign an IP based on its routing table. As the result depends on the IP you'd like to connect to, there is a simple trick: Simply create a connection and see what address you've got from the OS:
// output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();
// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());
I'm not sure whether it's possible to do this without establishing a connection though. I think I've once managed to do it with Perl (or C?), but don't ask me about Java. I think it might be possible to create a UDP socket (DatagramSocket) without actually connecting it.
If there is a NAT router on the way you won't be able to get the IP that remote hosts will see though. However, as you gave 192.* as an example, I think you don't care.
Upvotes: 23
Reputation: 345
In case you want to get the IP address of your PC, you have to use the "InetAddress" object, which exists in "java.net.InetAddress" library.
The following method returns your IP:
public String getIp() {
String myIp = "";
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
myIp = ip.getHostAddress(); // This method returns the IP.
} catch (UnknownHostException e) {
e.printStackTrace();
}
return myIp;
}
Upvotes: -6
Reputation: 339
Get the current request from the current instance
HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
then get the address from the request
ip = httpServletRequest.getRemoteAddr();
Upvotes: 1
Reputation: 1955
Here is a way to avoid IPv6 and Loopback results.
public InetAddress getCurrentIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces
.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while(nias.hasMoreElements()) {
InetAddress ia= (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress()
&& !ia.isLoopbackAddress()
&& ia instanceof Inet4Address) {
return ia;
}
}
}
} catch (SocketException e) {
LOG.error("unable to get current IP " + e.getMessage(), e);
}
return null;
}
Upvotes: 11
Reputation: 317
To fix it:
Find your host name. Type: hostname
. For example, you find your hostname is mycomputer.xzy.com
Put your host name in your hosts file. /etc/hosts
. Such as
10.50.16.136 mycomputer.xzy.com
Upvotes: 18
Reputation: 5365
If you actually want to work with all of the IP addresses on the machine you can get those with the NetworkInterface class. Of course, then you need to which one you actually want to use, but that's going to be different depending on what you're using it for, or you might need to expand the way you're using it to account for multiple addresses.
import java.net.*;
import java.util.*;
public class ShowInterfaces
{
public static void main(String[] args) throws Exception
{
System.out.println("Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
System.out.println("Interface: " + e.getName());
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
}
}
Upvotes: 36
Reputation: 182878
Your computer may have multiple IPs. How do you know which one? The way I do it is to have a very simple CGI running on another machine that reports back the IP it's seen, and I hit that when I need to know what my IP looks like to the outside world.
Upvotes: 3