现在的位置: 首页 > 综合 > 正文

获取ip地址

2018年04月25日 ⁄ 综合 ⁄ 共 1265字 ⁄ 字号 评论关闭
import java.net.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
    
public class showip extends JFrame implements ActionListener{
    private JTextField jTextField;
    private JLabel jLabel1,jLabel2;
    private JButton jButton;
    public showip()
    {
        super("获取本机IP");
        jButton=new JButton("获取IP");
        jLabel1=new JLabel("请输入主机名:");
        jLabel2=new JLabel();
        jTextField=new JTextField();
        this.setLayout(null);
        jLabel1.setBounds(10, 30, 100, 30);
        jTextField.setBounds(110, 30, 100, 30);
        jButton.setBounds(210, 30, 100, 30);
        jButton.addActionListener(this);
        this.add(jLabel1);
        this.add(jTextField);
        this.add(jButton);
        this.add(jLabel2);
        this.setLocation(200,200);
        this.setSize(350,200);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new showip();
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource()==jButton) {
            String str="",name=this.jTextField.getText().trim();//去除空格
            if(name.matches(str))
            {
                JOptionPane.showMessageDialog(getParent(),"请输入您要查看IP的电脑名!");
                jTextField.requestFocus();
            }
            else {
                InetAddress str1 = null;
                String ip=null;
                try {
                    str1 = InetAddress.getByName(name);
                    ip=str1.getHostAddress();
                } 
                catch (UnknownHostException e1) 
                {
                    e1.printStackTrace();
                }
                this.jLabel2.setBounds(10, 60, 200, 30);
                this.jLabel2.setText("目的主机的IP为:"+ip);
            }
        }
    }
}

抱歉!评论已关闭.