java代码获得本地ip,java获取本地地址
如何用java获取本地ip地址
import java.net.Inet4Address;
为大兴等地区用户提供了全套网页设计制作服务,及大兴网站建设行业解决方案。主营业务为成都网站建设、成都网站制作、大兴网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @author Becolette
* @description TODO
* @date 2015-11-5 下午01:58:46
*/
public class IpAddress {
public static String find() {
ListString ips = new ArrayListString();
// 返回所有网络接口的一个枚举实例
Enumeration? allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
EnumerationInetAddress addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
// 获得当前网络接口
ip = (InetAddress) addresses.nextElement();
if (ip != null ip instanceof Inet4Address ip.getHostAddress().indexOf(".") != -1) {
ips.add(ip.getHostAddress());
}
}
}
if (ips.size() == 1) {
return ips.get(0);
} else {
for (String ipa : ips) {
if (!"127.0.0.1".equals(ipa)) {
return ipa;
}
}
}
return MacAddress.find();
}
}
在Java程序中获取本机IP
import java.net.InetAddress;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.util.*;
public class ipdisplay {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String allipaddress;
ArrayList ar = new ArrayList();
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration cardipaddress = ni.getInetAddresses();
InetAddress ip = (InetAddress) cardipaddress.nextElement();
if(!ip.getHostAddress().equalsIgnoreCase("127.0.0.1") )
{ ar.add(ni.getName()+":");
allipaddress=ip.getHostAddress();
while(cardipaddress.hasMoreElements())
{
ip = (InetAddress) cardipaddress.nextElement();
allipaddress=allipaddress+" , "+ip.getHostAddress();
}
ar.add(allipaddress);
}
else
continue;
}
for(int i=0;iar.size();)
{
System.out.println(ar.get(i++));
}
}
}
JAVA怎么获取IP地址
这个是获取不到的,因为有代理、端口映射等等转发情况的存在。为什么不保存相对路径/域名/或者在服务器上某个配置文件中配置域名/数据库中一个表/数据库中某个字段保存当前服务器的ip地址呢?
java 如何提取本地IP
import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
String ip = InetAddress.getLocalHost().getHostAddress();
System.out.println(ip);
}
}
本文题目:java代码获得本地ip,java获取本地地址
标题网址:http://myzitong.com/article/hsihch.html