如何使用java获得本机IP和名称

package com.test;

import java.net.InetAddress;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class IPlable {
JFrame frame;
JLabel labell, label2;
String IP, address;
JPanel panel;
public void getIP() {
try {
InetAddress addr = InetAddress.getLocalHost();
IP = addr.getHostAddress().toString();
address = addr.getHostName().toString();
//System.out.println("IP="+IP);
//System.out.println("address="+address);
} catch (Exception e) {
e.printStackTrace();
}
}

public void showFrame(){
frame = new JFrame(
"my IP");
labell = new JLabel(
"this my IP");
labell.setText(IP);
label2 = new JLabel(
"this my address");
label2.setText(address);
panel = new JPanel();
panel.add(labell);
panel.add(label2);
frame.getContentPane().add(panel);

frame.setSize(400, 300);
frame.setVisible(true);
}

public static void main(String[] args) {
IPlable l = new IPlable();
l.getIP();
l.showFrame();
}

}

lunzi   2008-08-01 16:44:42 评论:2   阅读:4497   引用:0
无题 @2008-08-01 20:44:35  lunzi
嗯,两种都可以,我一直用你说的这种,request方式是基于servlet容器的,脱离了容器就不能试用了。这种可以在普通java类直接试用,试用范围更大一些。
无题 @2008-08-01 17:32:22  weiking
request.getRemoteAddr()  // 本机IP
request.getRemoteHost()  //主机名称

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog