我正在尝试用Java获取我的Internet IP地址,但是当我的IP地址为192.168.0.xxx
时,我会继续获取本地地址(即:127.0.0.1)我正在使用该行:
InetAddress.getLocalHost().getHostAddress();
这似乎是获取IP地址的标准,但它不是我想要的。每个教程都说使用这一行,所以我有点困惑。
有人可以告诉我如何获取正确的IP地址吗?
我在连接到WiFi的设备上运行,我没有使用任何电缆。我使用ifconfig inet addr给出的IP连接到服务器,我希望得到设备的inet addr。我可以检查服务器端套接字的IP,但是如果设备(客户端)告诉服务器他希望其他设备连接哪个IP,那就更好了。
答案 0 :(得分:38)
String ip;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
System.out.println(iface.getDisplayName() + " " + ip);
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
答案 1 :(得分:18)
NetworkInterface
类包含所有相关方法,但请注意,没有“我的IP”这样的东西。一台机器可以有多个接口,每个接口可以有多个IP。
您可以使用此类列出所有内容,但您从列表中选择的接口和IP取决于您使用此IP所需的内容。
(InetAddress.getLocalHost()
不咨询您的接口,它只返回常量127.0.0.1(对于IPv4))
答案 2 :(得分:9)
URL url = new URL("http://checkip.amazonaws.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
System.out.println(br.readLine());
修改强>
在你投票之前,我很清楚这不是一个java解决方案。它是任何编程语言的通用解决方案。其他解决方案对我来说效果不佳。另外我相信知道你的IP更简单的方法就是上网。它可以是任何站点,服务器可以返回它在请求中获得的客户端ip。您可以为它设置自己的端点。
答案 3 :(得分:3)
默认网络接口的另一个选项,就是我在5分钟前尝试并看到了你的问题:)
InetAddress[] localaddr;
try {
localaddr = InetAddress.getAllByName("host.name");
for(int i = 0; i < localaddr.length; i++){
System.out.println("\n" + localaddr[i].getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
答案 4 :(得分:3)
遇到同样的问题,请在此页面找到解决方案:http://mrhawy.blogspot.it/2012/05/how-to-get-your-external-ip-address-in.html
public String getIpAddress() throws MalformedURLException, IOException {
URL myIP = new URL("http://api.externalip.net/ip/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
}
从长远来看,这个代码遇到了一些麻烦,服务器一周内几次都没有多次回复。
新解决方案:
public static String getIpAddress()
{
URL myIP;
try {
myIP = new URL("http://api.externalip.net/ip/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e)
{
try
{
myIP = new URL("http://myip.dnsomatic.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e1)
{
try {
myIP = new URL("http://icanhazip.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(myIP.openStream())
);
return in.readLine();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return null;
}
答案 5 :(得分:2)
//This program is find your exact LAN(Local Machine on which your are //runing this program) IP Address
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetMyIPAddress {
public static void main(String gks[]) throws SocketException{
Enumeration e = NetworkInterface.getNetworkInterfaces();
int ctr=0;
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements() && ctr<3)
{ ctr++;
if(ctr==3)
break;
InetAddress i = (InetAddress) ee.nextElement();
if(ctr==2)
System.out.println(i.getHostAddress());
}
}
}
}
答案 6 :(得分:2)
我的解决方案只返回1个Ip4地址:
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
final String ip = addr.getHostAddress();
if(Inet4Address.class == addr.getClass()) return ip;
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return null;
答案 7 :(得分:2)
以下是获取IP地址的方法。
请参阅下面的完整工作代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class MyIpAddress {
public static void main(String[] args) {
// doPortForwarding();
MyIpAddress myIpAddress = new MyIpAddress();
// get default address
String yourIp = myIpAddress.getYourIp(myIpAddress
.getDefaultGateWayAddress());
System.out.println(yourIp);
// get
} // amin
// return ip address for which u need to do port forwarding
private String getYourIp(String defaultAddress) {
String temp = defaultAddress.substring(0, 11);
String ipToForward = "";
TreeSet<String> ipAddrs = getIpAddressList();
for (Iterator<String> iterator = ipAddrs.iterator(); iterator.hasNext();) {
String tempIp = iterator.next();
if (tempIp.contains(temp)) {
ipToForward = tempIp;
break;
}
}
return ipToForward;
}// ipForPortForwarding
// get the ipaddress list
private TreeSet<String> getIpAddressList() {
TreeSet<String> ipAddrs = new TreeSet<String>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ipAddrs.add(addr.getHostAddress());
}// 2 nd while
}// 1 st while
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ipAddrs;
}// getIpAddressList
// get default gateway address in java
private String getDefaultGateWayAddress() {
String defaultAddress = "";
try {
Process result = Runtime.getRuntime().exec("netstat -rn");
BufferedReader output = new BufferedReader(new InputStreamReader(
result.getInputStream()));
String line = output.readLine();
while (line != null) {
if (line.contains("0.0.0.0")) {
StringTokenizer stringTokenizer = new StringTokenizer(line);
stringTokenizer.nextElement();// first string is 0.0.0.0
stringTokenizer.nextElement();// second string is 0.0.0.0
defaultAddress = (String) stringTokenizer.nextElement(); // this is our default address
break;
}
line = output.readLine();
}// while
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return defaultAddress;
}// getDefaultAddress
}
答案 8 :(得分:0)
你需要获得jsoup here的jar 在你的java项目中添加jsoup jar并解释这行代码,你将得到你的ip地址,
Document doc = Jsoup.connect("https://whatismyipaddress.com/").timeout(10000).get() ;
Elements el = doc.select("div#section_left") ;
Element e = el.select("a").get(
System.out.println(e.text());
答案 9 :(得分:0)
您可以通过编写简单的代码来获取IP地址。 `
import java.net.InetAddress;
public class Main {
public static void main(String[] args) throws Exception
{
System.out.println(InetAddress.getLocalHost());
}
}