package ByIpGainDomainFrame;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class ByIpGainDomainFrame extends JFrame {
private JLabel title_label;
private JLabel ip_label;
private JLabel canonical_label;
private JLabel host_label;
private JTextField tf_ip;
private JTextField tf_canonical;
private JTextField tf_host;
private JButton get_button;
private JButton exit_button;
private JPanel north;
private JPanel south;
private JPanel center;
public ByIpGainDomainFrame(){
north=new JPanel();
title_label=new JLabel("通过IP地址获得域名和主机名");
north.add(title_label);
add(north,BorderLayout.NORTH);
center=new JPanel();
center.setLayout(new GridLayout(3,2));
ip_label=new JLabel(" 输入IP地址:",SwingConstants.RIGHT);
tf_ip=new JTextField("",20);
center.add(ip_label);
center.add(tf_ip);
host_label=new JLabel("主机名:",SwingConstants.RIGHT);
tf_host=new JTextField("",20);
center.add(host_label);
center.add(tf_host);
canonical_label=new JLabel("域名:",SwingConstants.RIGHT);
tf_canonical=new JTextField("",20);
center.add(canonical_label);
center.add(tf_canonical);
add(center,BorderLayout.CENTER);
south=new JPanel();
get_button=new JButton("获得主机名和域名");
exit_button=new JButton("退出系统");
south.add(get_button);
south.add(exit_button);
add(south,BorderLayout.SOUTH);
get_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//获取输入的ip地址
String ip=tf_ip.getText();
//以字符“.”分割ip地址,并以字符串形式存储在ipStr数组中
String[] ipStr=ip.split("[.]");
//getByAddress需要一个字节数组参数,
byte[] ipBytes=new byte[4];
for(int i=0;i<4;i++){
//ip字符串转换成整数
int m=Integer.parseInt(ipStr[i]);
//byte类型的数字要&0xff再赋值给int类型,其本质原因就是想保持二进制补码的一致性
byte b=(byte)(m&0xff);
ipBytes[i]=b;
}
try {
//通过IP地址获得inetAddress实例
InetAddress inetAddr=InetAddress.getByAddress(ipBytes);
//获取域名
String canonical=inetAddr.getCanonicalHostName();
//获取计算机名
String host=inetAddr.getHostName();
tf_canonical.setText(canonical);
tf_host.setText(host);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
exit_button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
pack();
}
}