论坛首页 Java企业应用论坛

用java获取本地ip

浏览 31983 次
精华帖 (1) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-03-10  
通常,我们都是用以下代码来获取本地ip地址的
InetAddress.getLocalHost().getHostAddress()

这种方法在linux却只能取到127.0.0.1这个让人无奈的地址。。。这简直是让人不能忍受的啊。。。这种地址不用获取,我们谁不知道。。。
在网上搜索了很多,发现说这个问题的并不多,所以,我把找到的一段代码分享给大家。。。当然这段代码需要jdk1.5以上版本
Enumeration<NetworkInterface> netInterfaces = null;
try {
	netInterfaces = NetworkInterface.getNetworkInterfaces();
	while (netInterfaces.hasMoreElements()) {
		NetworkInterface ni = netInterfaces.nextElement();
		System.out.println("DisplayName:" + ni.getDisplayName());
		System.out.println("Name:" + ni.getName());
		Enumeration<InetAddress> ips = ni.getInetAddresses();
		while (ips.hasMoreElements()) {
			System.out.println("IP:"
			+ ips.nextElement().getHostAddress());
		}
	}
} catch (Exception e) {
	e.printStackTrace();
}

这段代码会输出计算机中所有设备的ip,找需要的用吧,呵呵
   发表时间:2008-03-10  
public String getLocalIP(){
InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
                        return null;
		}
		byte[] ipAddr = addr.getAddress();
		String ipAddrStr = "";
		for (int i = 0; i < ipAddr.length; i++) {
			if (i > 0) {
				ipAddrStr += ".";
			}
			ipAddrStr += ipAddr[i] & 0xFF;
		}
		//System.out.println(ipAddrStr);
                return ipAddrStr;
}
0 请登录后投票
   发表时间:2008-03-16  
如何获取外网的IP???
0 请登录后投票
   发表时间:2008-03-16  
saturn 写道
如何获取外网的IP???

连接一个外部网站,对返回的数据中解析出IP内容。
当然目标网站是一个汇报client IP地址的网页。

否则你再怎么枚举也枚举不到外网IP,如果你处在防火墙内
0 请登录后投票
   发表时间:2008-03-18  
引用
Java代码


  
引用
1. 如何获取外网的IP??? 
0 请登录后投票
   发表时间:2008-05-08  
ServletActionContext.getRequest().getLocalAddr();
ServletActionContext.getRequest().getLocalName();
ServletActionContext.getRequest().getLocalPort();
或者
String serverIP = ServletActionContext.getRequest().getServerName();
int serverPort = ServletActionContext.getRequest().getServerPort();

0 请登录后投票
   发表时间:2008-05-13  
Process proc=Runtime.getRuntime().exec("ping "+ip +" -w 300 -n 1");
//通过调用系统的PING命令,来获得局域网IP
BufferedReader read=new BufferedReader(new InputStreamReader(proc.getInputStream()));
String str="";
for (int i = 0; i < 7; i++)
str=read.readLine();
if(str.length()<17 || str.indexOf("timed out")!=-1){
//map.put(ip, new Boolean(false));
}else{
InetAddress addr=InetAddress.getByName(ip);
map.put(addr.getHostName(),ip);
}
0 请登录后投票
   发表时间:2008-05-13  
public abstract class IPUtils {
	
	private static Log logger = LogFactory.getLog(IPUtils.class);
	
	public static Collection<InetAddress> getAllHostAddress() {
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			Collection<InetAddress> addresses = new ArrayList<InetAddress>();
			
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces.nextElement();
				Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					InetAddress inetAddress = inetAddresses.nextElement();
					addresses.add(inetAddress);
				}
			}
			
			return addresses;
		} catch (SocketException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public static Collection<String> getAllNoLoopbackAddresses() {
		Collection<String> noLoopbackAddresses = new ArrayList<String>();
		Collection<InetAddress> allInetAddresses = getAllHostAddress();
		
		for (InetAddress address : allInetAddresses) {
			if (!address.isLoopbackAddress()) {
				noLoopbackAddresses.add(address.getHostAddress());
			}
		}
		
		return noLoopbackAddresses;
	}
	
	public static String getFirstNoLoopbackAddress() {
		Collection<String> allNoLoopbackAddresses = getAllNoLoopbackAddresses();
		Assert.isTrue(!allNoLoopbackAddresses.isEmpty(), " Sorry, seems you don't have a network card :( ");
		return allNoLoopbackAddresses.iterator().next();
	}
}	
0 请登录后投票
   发表时间:2008-05-17  
/**
* @see javax.servlet.ServletRequestWrapper#getRemoteAddr()
*/
public String getRemoteAddr()
{
// We look if the request is forwarded
// If it is not call the older function.
        String ip = super.getHeader("x-forwarded-for");
       
        if (ip == null) {
        ip = super.getRemoteAddr();
        }
        else {
        // Process the IP to keep the last IP (real ip of the computer on the net)
            StringTokenizer tokenizer = new StringTokenizer(ip, ",");

            // Ignore all tokens, except the last one
            for (int i = 0; i < tokenizer.countTokens() -1 ; i++) {
            tokenizer.nextElement();
            }
           
            ip = tokenizer.nextToken().trim();
           
            if (ip.equals("")) {
            ip = null;
            }
        }
       
        // If the ip is still null, we put 0.0.0.0 to avoid null values
        if (ip == null) {
        ip = "0.0.0.0";
        }
       
        return ip;
}

0 请登录后投票
   发表时间:2008-05-18  
楼上  人家都说了是获取本地 IP 了  你贴个 getRemoteAddr() 干啥
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics