首页 > 代码库 > java如何获取IP地址

java如何获取IP地址

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
public class GetMacIp {
 
       /**  
       * @Title: main 
       * @Description: TODO
       * @param :@param args     
       * @return :void    
       * @throws 
       */
       public static void main(String[] args) {
            
                    String currentIP= null;
                    Enumeration<?> e1;
                    try {
                        e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
                        while (e1.hasMoreElements()) {
                            NetworkInterface ni = (NetworkInterface) e1.nextElement();
                            if (!ni.getName().equals("eth3" )) {
                                continue;
                            } else {
                                Enumeration<?> e2 = ni.getInetAddresses();
                                while (e2.hasMoreElements()) {
                                    InetAddress ia = (InetAddress) e2.nextElement();
                                    if (ia instanceof Inet6Address) {
                                        continue;
                                    }
                                   currentIP = ia.getHostAddress();
                                   
                                }
                                System. out.println("======" +currentIP);
                                break;
                            }
                        }
                    } catch (SocketException e) {
                        e.getMessage();
                    }
 
                }
 
      }