论坛首页 入门技术论坛

获取IP地址

浏览 3929 次
锁定老帖子 主题:获取IP地址
精华帖 (0) :: 良好帖 (0) :: 新手帖 (8) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-11-25   最后修改:2010-11-25
package com.tianren.service;
import java.net.*;

import sun.security.krb5.internal.HostAddress;

public class Test{
 InetAddress myIPaddress = null;
 InetAddress myServer = null;
 String hostAddress = null;
 String hostName = null;
 String Address = null ;
 String Name = null ;
 public static void main(String args[]) {

  Test mytool;
  mytool = new Test();
  mytool.getAllServerIP();
//  System.out.println("Your host IP is: " + mytool.getMyIP());
//  System.out.println("The Server IP is :" + mytool.getServerIP());
}

 // 取得LOCALHOST的IP地址
 public String getMyIP() {
  try {
   myIPaddress = InetAddress.getLocalHost();
   hostAddress = myIPaddress.getHostAddress();//仅仅获得IP地址
   hostName = myIPaddress.getHostName();//获得本地名称
  } catch (UnknownHostException e) {
  }
  return (hostName);
 }

 // 取得 www.abc.com 的IP地址
 public String getServerIP() {
  try {
   myServer = InetAddress.getByName("www.abc.com");
   Address = myServer.getHostAddress();//获得www.abc.com的ip地址
   Name = myServer.getHostName();//获得域名
  } catch (UnknownHostException e) {
  }
  return (Name);
 }
 //获取此域名下的所有IP
 public void getAllServerIP(){
  String name = "www.microsoft.com";
  try{
   
   InetAddress[] addresses= InetAddress.getAllByName(name);
   for(int i =0;i<addresses.length;i++){
    System.out.println(addresses[i].getHostAddress());
   }
  }catch(Exception e){
   System.err.println("Unable to find: "+name);

  }
 }

}

   发表时间:2010-11-25  
对于linux获得本机ip可能得到的是127.0.0.1。
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics