《java》中如何提取本地IP?
《java》中提取本地IP的方法如下:
private static void getIpAddressByNetworkInterface() {
try {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
NetworkInterface net;
InetAddress inetAddress;
while (nets.hasMoreElements()) {
net = nets.nextElement();
Enumeration<InetAddress> 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();
}
}
获取本地ip的方法。
System.out.println(InetAddress.getLocalHost().getHostAddress());
域名解析ip的方法。
System.out.println(InetAddress.getByName("www.sina.com.cn"));
获取本地出口ip的方法(局域网NAT或本地找交换机出口ip的方法),建立通讯TCP,telnet,mina通讯等。
Socket client = new Socket("192.168.6.8", 80);
System.out.println(client.getInetAddress().getHostAddress());import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
String ip = InetAddress.getLocalHost().getHostAddress();
System.out.println(ip);
}
}