InetAddress,Socket
大侠们给看看
一、
import java.net.*;
import java.io.*;
public class JLookup
{
public static void main(String args[])
{
if(args.length > 0)
{
for(int i = 0; i < args.length; i++)
{
lookup(args[i]);
System.out.println();
}
}
else
{
System.out.println("Enter a hostname or IP.(\"Q\" to Quit)");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
try
{
String prompt = "JLookup>";
System.out.print(prompt);
String line = input.readLine().trim();
if(line.equalsIgnoreCase("Q"))
{
input.close();
break;
}
lookup(line);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
private static void lookup(String host)
{
InetAddress hostInetAddr[] = null;
try
{
hostInetAddr = InetAddress.getAllByName(host);
System.out.println("hostInetAddr = " + hostInetAddr);
/*hostInetAddr = InetAddress.getLocalHost();
System.out.println("hostInetAddr = " + hostInetAddr);*/
}
catch(UnknownHostException e)
{
System.out.println("Unknown Host:"+host);
}
if(isHostname(host))
{
for(int i = 0; i < hostInetAddr.length; i++)
{
System.out.println(hostInetAddr[i].getHostAddress());
}
}
else
{
for(int i = 0; i < hostInetAddr.length; i++)
{
System.out.println(hostInetAddr[i].getHostName());
}
}
}
private static boolean isHostname(String host)
{
char[] chHost = host.trim().toCharArray();
for(int i = 0; i < chHost.length; i++)
{
if(chHost[i] != '.' && (chHost[i] < '0' || chHost[i] > '9' ))
{
return true;
}
}
return false;
}
}
在别人电脑上直接执行OK,我直接执行不行,但是我在控制台下却可以?
二、
import java.net.*;
import java.io.*;
public class JTimeClient
{
private String server; //时间服务器
private int port; //端口号
public JTimeClient(String server)
{
this(server,37); //时间服务器默认端口号
}
public JTimeClient(String server,int port)
{
this.server = server;
this.port = port;
}
//返回网络时间,-1表示出错
public long getNetTime()
{
Socket socket = null;
InputStream in = null;
try
{
socket = new Socket(server,port);
//时间服务器
in = socket.getInputStream();
//读取数据,网络时间为4字节无符号整数
//表示基于1900年元月1日0点的秒数
long netTime = 0;
for(int i = 0; i < 4; i++)
{
netTime = (netTime << 8) | in.read();
}
return netTime;
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
//安全释放资源
try
{
if(in != null)
{
in.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
//关闭连接
try
{
if(socket != null)
{
socket.close();
}
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
}
}
return -1;
}
public static void main(String args[])
{
JTimeClient timeClient = null;
if(args.length == 1)
{
timeClient = new JTimeClient(args[0]);
}
else if(args.length == 2)
{
timeClient = new JTimeClient(args[0],Integer.parseInt(args[1]));
}
else
{
System.out.println("Usage: java JTimeClient TimeServer Port");
return;
}
System.out.println("Time:"+timeClient.getNetTime());
}
}
不行
为啥啊?帮帮忙啊