当前位置: 技术问答>java相关
我这样可以取得本地ip地址么?
来源: 互联网 发布时间:2015-05-21
本文导语: 我这样可以取得本地ip地址么? import java.io.*; import java.net.*; public class Test { public static void main(String args[]) { Socket s = new Socket(InetAddress.getLocalHost(),8500); System.out.println(s.getInetAddress()); } } 有错么?怎么取得本...
我这样可以取得本地ip地址么?
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String args[])
{
Socket s = new Socket(InetAddress.getLocalHost(),8500);
System.out.println(s.getInetAddress());
}
}
有错么?怎么取得本地的ip?
import java.io.*;
import java.net.*;
public class Test
{
public static void main(String args[])
{
Socket s = new Socket(InetAddress.getLocalHost(),8500);
System.out.println(s.getInetAddress());
}
}
有错么?怎么取得本地的ip?
|
Socket s = new Socket(InetAddress.getLocalHost(),8500);
这个不行
改为:
InetAddress addr = InetAddress.getByName("localhost");
Socket s = new Socket(addr,8500);
就行
这个不行
改为:
InetAddress addr = InetAddress.getByName("localhost");
Socket s = new Socket(addr,8500);
就行
|
不需要用socket,因为它会涉及到安全性问题。只需要InetAddress就可以了。使用如下代码:
try{
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.toString());
}catch (UnknownHostException e){
e.printStackTrace();
};
}
try{
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.toString());
}catch (UnknownHostException e){
e.printStackTrace();
};
}