本例需要被找的机器同时也在运行以下代码。目前是遍历所有IP进行查找,效率很低,在没找到更好的办法之前只好用它了。
/**
* 在局域网(LAN)里面根据主机名找到对应的IP。
* 设计作者: teasp
* 信息描述:
*/
public class IpHostInLan
{
private static final int PORT = 4321;
private static final String NOT_FOUND = "NotFound";
private ConcurrentHashMap<String, String> map = new ConcurrentHashMap<String, String>();
private static IpHostInLan instance = new IpHostInLan();
private volatile String resultIp = null;
private IpHostInLan()
{
new Thread()
{
public void run()
{
try
{
String localHost = InetAddress.getLocalHost().getHostName();
ServerSocket ss = new ServerSocket(PORT);
System.out.println("--------Listening to " + PORT + "----------");
while (true)
{
Socket socket = ss.accept();
try
{
socket.getOutputStream().write(localHost.getBytes());
socket.getOutputStream().fl