《java》中如何提取本地IP?

2025-02-22 10:42:35
推荐回答(2个)
回答1:

《java》中提取本地IP的方法如下:

private static void getIpAddressByNetworkInterface() {

try {

Enumeration nets = NetworkInterface.getNetworkInterfaces();    

NetworkInterface net;

InetAddress inetAddress;

while (nets.hasMoreElements()) {

net = nets.nextElement();

Enumeration address = net.getInetAddresses();

while (address.hasMoreElements()) {

inetAddress = address.nextElement();

if (inetAddress!=null&&inetAddress instanceof Inet4Address)

System.out.println(inetAddress.getHostAddress());

}

}

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

回答2:

  1. 获取本地ip的方法。

  2. System.out.println(InetAddress.getLocalHost().getHostAddress());
  3. 域名解析ip的方法。

  4. System.out.println(InetAddress.getByName("www.sina.com.cn"));

  5. 获取本地出口ip的方法(局域网NAT或本地找交换机出口ip的方法),建立通讯TCP,telnet,mina通讯等。

  6. Socket client = new Socket("192.168.6.8", 80);  
    System.out.println(client.getInetAddress().getHostAddress());
  7. import java.net.*;
    public class Test {
       public static void main(String[] args) throws Exception {
            String ip = InetAddress.getLocalHost().getHostAddress();
            System.out.println(ip);
       }
    }