Linux下用Java获取本机IP地址的方法
时间:2010-06-07 来源:seans88
在linux下用InetAddress.getLocalHost().getHostAddress()会出现 127.0.0.1 ?
原因:这个是etc/hosts文件中的配置,并非网卡的IP地址。
解决办法:
public class GetIP {
public String getMacAddr() {
String MacAddr = "";
String str = "";
try {
NetworkInterface NIC = NetworkInterface.getByName("eth0");
byte[] buf = NIC.getHardwareAddress();
for (int i = 0; i < buf.length; i++) {
str = str + byteHEX(buf[i]);
}
MacAddr = str.toUpperCase();
} catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
return MacAddr;
}
public String getLocalIP() {
String ip = "";
try {
Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
if (!ni.getName().equals("eth0")) {
continue;
} else {
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address)
continue;
ip = ia.getHostAddress();
}
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
return ip;
}
public String byteHEX(byte ib) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f' };
char[] ob = new char[2];
ob[0] = Digit[(ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
}
参考:http://www.pczpg.com/a/2010/0421/6115.html
原因:这个是etc/hosts文件中的配置,并非网卡的IP地址。
解决办法:
public class GetIP {
public String getMacAddr() {
String MacAddr = "";
String str = "";
try {
NetworkInterface NIC = NetworkInterface.getByName("eth0");
byte[] buf = NIC.getHardwareAddress();
for (int i = 0; i < buf.length; i++) {
str = str + byteHEX(buf[i]);
}
MacAddr = str.toUpperCase();
} catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
return MacAddr;
}
public String getLocalIP() {
String ip = "";
try {
Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
if (!ni.getName().equals("eth0")) {
continue;
} else {
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address)
continue;
ip = ia.getHostAddress();
}
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
System.exit(-1);
}
return ip;
}
public String byteHEX(byte ib) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f' };
char[] ob = new char[2];
ob[0] = Digit[(ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
}
参考:http://www.pczpg.com/a/2010/0421/6115.html
相关阅读 更多 +