java:得到本机或网站的IP和计算机名称

来源:互联网 发布:网络配置实例 编辑:程序博客网 时间:2024/05/14 04:10

package com.happy.host;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;

public class GetIp {
 public static void main(String[] args) {
  try {
      InetAddress addr = InetAddress.getLocalHost();

      // Get IP Address
      byte[] ipAddr = addr.getAddress();
      String ipAddrStr = "";
      for (int i=0; i<ipAddr.length; i++) {
          if (i > 0) {
              ipAddrStr += ".";
          }
          ipAddrStr += ipAddr[i]&0xFF;
      }

      // Get hostname
      String hostname = addr.getHostName();
      System.out.println(ipAddrStr+hostname);
  } catch (UnknownHostException e) {
  }
  
  try {
      InetAddress addr = InetAddress.getByName("javaalmanac.com");
      byte[] ipAddr = addr.getAddress();

      // Convert to dot representation
      String ipAddrStr = "";
      for (int i=0; i<ipAddr.length; i++) {
          if (i > 0) {
              ipAddrStr += ".";
          }
          ipAddrStr += ipAddr[i]&0xFF;
      }
      System.out.println(ipAddrStr);
  } catch (UnknownHostException e) {
  }
  
  try {
      // Get hostname by textual representation of IP address
      InetAddress addr = InetAddress.getByName("127.0.0.1");

      // Get hostname by a byte array containing the IP address
      byte[] ipAddr = new byte[]{127, 0, 0, 1};
      addr = InetAddress.getByAddress(ipAddr);

      // Get the host name
      String hostname = addr.getHostName();

      // Get canonical host name
      String hostnameCanonical = addr.getCanonicalHostName();
      System.out.println(hostname+hostnameCanonical);
  } catch (UnknownHostException e) {
  }

 }
}

原创粉丝点击