java通过域名怎么获取本机ip

发布网友 发布时间:2022-04-24 18:41

我来回答

4个回答

热心网友 时间:2022-05-19 13:27

代码亲测可用:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestInetAddress {
InetAddress myIpAddress = null;
InetAddress[] myServer = null;

public static void main(String args[]) {
TestInetAddress address = new TestInetAddress();
System.out.println("Your host IP is: " + address.getLocalhostIP());

String domain = "www.163.com";
System.out.println("The server domain name is: " + domain);
InetAddress[] array = address.getServerIP(domain);
int count=0;
for(int i=1; i<array.length; i++){
System.out.println("ip "+ i +" "+ address.getServerIP(domain)[i-1]);
count++;
}
System.out.println("IP address total: "+count);
}

/**
* 获得 localhost 的IP地址
* @return
*/
public InetAddress getLocalhostIP() {
try {
myIpAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return (myIpAddress);
}

/**
* 获得某域名的IP地址
* @param domain 域名
* @return
*/
public InetAddress[] getServerIP(String domain) {
try {
myServer = InetAddress.getAllByName(domain);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return (myServer);
}

}

热心网友 时间:2022-05-19 14:45

本机用cmd ipconfig 或者百度ip就可以了

热心网友 时间:2022-05-19 16:20

public String getIP(String name){
InetAddress address = null;
try {
address = InetAddress.getByName(name);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("获取失败");
}
return address.getHostAddress().toString();
}

热心网友 时间:2022-05-19 18:11

import java.net.InetAddress;
import java.net.UnknownHostException;
public class NsLookup {
static public void main(String[] args) {
try {
System.out.println("try");
InetAddress address = InetAddress.getByName(args[0]);
System.out.println(args[0]+" : "+address.getHostAddress());

}catch(UnknownHostException uhe) {
System.out.println("catch");
System.err.println("Unable to find: "+args[0]);

}
}

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com