1.编写一个程序,查找指定域名为www.taobao.com的所以可能的ip地址。
public class Tb {
public static void main(String[] args) {
try {
InetAddress add=InetAddress.getByName("www.taobao.com"); //查找指定ip名
System.out.println("---------------淘宝的主服务器地址------------------");
System.out.println(add);
System.out.println("---------------淘宝的所有服务器地址-----------------");
InetAddress [] add1=InetAddress.getAllByName("taobao.com");
System.out.println(add);
for (int i = 0; i < add1.length; i++) { //利用循环打印
System.out.println("www."+add1[i]);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2.模拟用户登录,预设用户数据,提示登录成功或不成功的原因。
/*
* 服务端
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8800);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream(); // 读取流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = "";
StringBuffer sb = new StringBuffer();
while ((info = br.readLine()) != null) {
System.out.println("我是服务器,客户端登录信息为:" + info);
sb.append(info);
}
socket.shutdownInput(); // 先关闭输入流
OutputStream os = null;
String sum = sb.toString();
if (sum.equals("用户1") || sum.equals("用户2") || sum.equals("用户3")) { // 判断用户名
info = "欢迎你,登录成功!";
os = socket.getOutputStream();
os.write(info.getBytes());
System.out.println("存在该用户,用户登录成功");
} else {
info = "对不起,没有该用户,登录失败";
os = socket.getOutputStream();
os.write(info.getBytes());
System.out.println("对不起,没有该用户,已通知客户端登录失败");
}
os.close(); // 关流
br.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* 客户端
*/
public class Analog {
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost",8800);
Scanner input=new Scanner(System.in);
System.out.print("请输入用户名:");
String info=input.next();
OutputStream os=socket.getOutputStream();
byte [] infos=info.getBytes();
os.write(infos);
//接收
socket.shutdownOutput();//先关闭输出流
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String reply;
while ((reply=br.readLine())!=null){
System.out.println("我是客户端,服务器的响应为:"+reply);
}
br.close();
is.close();
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}