import javanetInetAddress;
import javanetUnknownHostException;
public class Test
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress inet = InetAddressgetLocalHost();
Systemoutprintln("本机的ip=" + inetgetHostAddress());
}
}
第一种:获取本机的IP
Enumeration<NetworkInterface>
netInterfaces
=
null;
try
{
netInterfaces
=
NetworkInterfacegetNetworkInterfaces();
while
(netInterfaceshasMoreElements())
{
NetworkInterface
ni
=
netInterfacesnextElement();
Systemoutprintln("DisplayName:"
+
nigetDisplayName());
Systemoutprintln("Name:"
+
nigetName());
Enumeration<InetAddress>
ips
=
nigetInetAddresses();
while
(ipshasMoreElements())
{
Systemoutprintln("IP:"
+
ipsnextElement()getHostAddress());
ipTemp=
nigetInetAddresses()nextElement()getHostAddress();
if(ipTemp!="127001"
&&
!"127001"equals(ipTemp))
{
ip=ipTemp;
}
}
}
}catch(Exception
ee)
{
eeprintStackTrace();
}
第二种:也是本机的:
InetAddress
addr
=
InetAddressgetLocalHost();
ip=addrgetHostAddress()toString();//获得本机IP
java获取本机的外网ip示例:
import javaioIOException;
import javaioInputStream;
import javanet>
import javanetInet4Address;
import javanetInetAddress;
import javanetNetworkInterface;
import javanetSocketException;
import javautilArrayList;
import javautilEnumeration;
import javautilList;
/
@author Becolette
@description TODO
@date 2015-11-5 下午01:58:46
/
public class IpAddress {
public static String find() {
List<String> ips = new ArrayList<String>();
// 返回所有网络接口的一个枚举实例
Enumeration<> allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterfacegetNetworkInterfaces();
} catch (SocketException e) {
eprintStackTrace();
}
InetAddress ip = null;
while (allNetInterfaceshasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfacesnextElement();
Enumeration<InetAddress> addresses = netInterfacegetInetAddresses();
while (addresseshasMoreElements()) {
// 获得当前网络接口
ip = (InetAddress) addressesnextElement();
if (ip != null && ip instanceof Inet4Address && ipgetHostAddress()indexOf("") != -1) {
ipsadd(ipgetHostAddress());
}
}
}
if (ipssize() == 1) {
return ipsget(0);
} else {
for (String ipa : ips) {
if (!"127001"equals(ipa)) {
return ipa;
}
}
}
return MacAddressfind();
}
}
以上就是关于怎样用JAVA程序获取本机ip 全部的内容,包括:怎样用JAVA程序获取本机ip 、java如何获取当前登录ip、Java怎样获取当前机器外网IP等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)