« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9692294 建立时间:2004年12月20日 |

| |
[java语言]java取本机ip的问题  原创空间, 软件技术, 电脑与网络
邢红瑞 发表于 2005/1/11 11:09:26 |
try { InetAddress localhost = InetAddress.getLocalHost(); System.out.println("localhost: " + localhost.getHostAddress()); System.out.println("localhost: " + localhost.getHostName());
} catch (UnknownHostException uhe) { System.err.println("Localhost not seeable. Something is odd. "); }windowXP下运行这个java没问题, 192.168.5.110 inux服务器下, ip为127.0.0.1getLocalHostpublic static InetAddress getLocalHost() throws UnknownHostException返回本地主机。 如果有安全管理器,则使用本地主机名和 -1 作为参数来调用其 checkConnect 方法,以查看是否允许该操作。如果不允许该操作,则返回表示回送地址的 InetAddress。
返回:本地主机的 IP 地址。 抛出: UnknownHostException - 如果找不到 host 的任何 IP 地址。另请参见:SecurityManager.checkConnect(java.lang.String, int)
getHostAddresspublic String getHostAddress()返回 IP 地址字符串(以文本表现形式)。
返回:字符串格式的原始 IP 地址。
在linux下返回127.0.0.1, 主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址, 而不是网卡的绑定地址 try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (netInterfaces.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement(); System.out.println(ni.getName()); ip = (InetAddress) ni.getInetAddresses().nextElement(); System.out.println("ip.isSiteLocalAddress():" + ip.isSiteLocalAddress()); System.out.println("ip.isLoopbackAddress():" + ip.isLoopbackAddress()); System.out.println("ip.getHostAddress():" + ip.getHostAddress()); } } catch (SocketException ex) { Logger.getLogger(TestString.class.getName()).log(Level.SEVERE, null, ex); }可以搞定其中SiteLocalAddress本机地址 LoopbackAddress回送地址 也可以使用Runtime运行本地命令得到, public final static String getMacAddress() throws IOException { String os = System.getProperty("os.name");
try { if (os.startsWith("Windows")) { return windowsParseMacAddress(windowsRunIpConfigCommand()); } else if (os.startsWith("Linux")) { return linuxParseMacAddress(linuxRunIfConfigCommand()); } else { throw new IOException("unknown operating system: " + os); } } catch (ParseException ex) { ex.printStackTrace(); throw new IOException(ex.getMessage()); } }
/* * Linux stuff */ private final static String linuxParseMacAddress(String ipConfigResponse) throws ParseException { String localHost = null; try { localHost = InetAddress.getLocalHost().getHostAddress(); } catch (java.net.UnknownHostException ex) { ex.printStackTrace(); throw new ParseException(ex.getMessage(), 0); }
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n"); String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) { String line = tokenizer.nextToken().trim(); boolean containsLocalHost = line.indexOf(localHost) >= 0;
// see if line contains IP address if (containsLocalHost && lastMacAddress != null) { return lastMacAddress; }
// see if line contains MAC address int macAddressPosition = line.indexOf("HWaddr"); if (macAddressPosition <= 0) continue;
String macAddressCandidate = line.substring(macAddressPosition + 6) .trim(); if (linuxIsMacAddress(macAddressCandidate)) { lastMacAddress = macAddressCandidate; continue; } }
ParseException ex = new ParseException("cannot read MAC address for " + localHost + " from [" + ipConfigResponse + "]", 0); ex.printStackTrace(); throw ex; }
private final static boolean linuxIsMacAddress(String macAddressCandidate) {// TODO: use a smart regular expression if (macAddressCandidate.length() != 17) return false; return true; }
private final static String linuxRunIfConfigCommand() throws IOException { Process p = Runtime.getRuntime().exec("ifconfig"); InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer(); for (; ; ) { int c = stdoutStream.read(); if (c == -1) break; buffer.append((char) c); } String outputText = buffer.toString();
stdoutStream.close();
return outputText; }
/* * Windows stuff */ private final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException { String localHost = null; try { localHost = InetAddress.getLocalHost().getHostAddress(); } catch (java.net.UnknownHostException ex) { ex.printStackTrace(); throw new ParseException(ex.getMessage(), 0); }
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n"); String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) { String line = tokenizer.nextToken().trim();
// see if line contains IP address if (line.endsWith(localHost) && lastMacAddress != null) { return lastMacAddress; }
// see if line contains MAC address int macAddressPosition = line.indexOf(":"); if (macAddressPosition <= 0) continue;
String macAddressCandidate = line.substring(macAddressPosition + 1) .trim(); if (windowsIsMacAddress(macAddressCandidate)) { lastMacAddress = macAddressCandidate; continue; } }
ParseException ex = new ParseException("cannot read MAC address from [" + ipConfigResponse + "]", 0); ex.printStackTrace(); throw ex; }
private final static boolean windowsIsMacAddress(String macAddressCandidate) {// TODO: use a smart regular expression if (macAddressCandidate.length() != 17) return false;
return true; }
private final static String windowsRunIpConfigCommand() throws IOException { Process p = Runtime.getRuntime().exec("ipconfig /all"); InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer(); for (; ; ) { int c = stdoutStream.read(); if (c == -1) break; buffer.append((char) c); } String outputText = buffer.toString();
stdoutStream.close();
return outputText; } |
|
|