2026年10月31日 · 今日 0 帖 · 会员 6.1万 · 主题 17.4万
登录 · 注册 · 游客,欢迎随便逛逛
返回版块
11406
Lv1韶华一笑间等级图标
帖子
62
回复
120
积分
2,076
注册
2011-02-07
[计算机网络]

使用java获取本机地址的示例【漫天教程】

[复制链接]
查看 605 回复 0
楼主 发表于 | 查看全部
76 人收藏

使用java获取本机地址的示例

*java*

/**

* Get my host IP address

* @author Administrator

*

*/

import java.util.Enumeration;

import java.net.*;

public class InetAddressExample {

public static void main(String** args){

//get the network interfaces and the associated addresses for this host

try{

Enumeration<NetworkInterface> interfaceList= NetworkInterface.getNetworkInterfaces();

if(interfaceList==null){

System.out.println(“No interfaces found!“);

}else{

while(interfaceList.hasMoreElements()){

NetworkInterface iface = interfaceList.nextElement();

System.out.println(“Interface:“+iface.getName()+“:“);

Enumeration<InetAddress> addrList = iface.getInetAddresses();

if (!addrList.hasMoreElements()) {

System.out.println(“\t(No addresses for this interface)“);

}

while (addrList.hasMoreElements()) {

InetAddress address = addrList.nextElement();

System.out.print(“\tAddress “+ ((address instanceof Inet4Address ? “(v4)“:

(address instanceof Inet6Address ? “(v6)“ : “(?)“))));

System.out.println(“: “ + address.getHostAddress());

}

}

}

}catch(SocketException se){

System.out.println(“Error getting network interfaces:“ + se.getMessage());

}

// Get name(s)/address(es) of hosts given on * line 34 for

for (String host : args) {

try{

System.out.println(host + “:“);

InetAddress** addressList = InetAddress.getAllByName(host);

for (InetAddress address : addressList) {

System.out.println(“\t“ + address.getHostName() + “/“ + address.getHostAddress());

}

}catch(UnknownHostException e){

System.out.println(“\tUnable to find address for “ + host);

}

}

}

}

登录回复

登录后可以回复这个帖子。旧账号可使用原密码登录。

登录 注册新号
← 返回版块