package com.xhpc.common.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class GetIpAndPort {

    private static String ip;
    private static final Logger log = LoggerFactory.getLogger(GetIpAndPort.class);

    //获取ip
    public static String getLocalIP() {
        if (ip==null) {
            String localIP = "127.0.0.1";
            try {
                OK:
                for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
                    NetworkInterface networkInterface = interfaces.nextElement();
                    if (!networkInterface.getName().equals("eth0") || networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                        continue;
                    }
                    log.info(networkInterface.getName());
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (address instanceof Inet4Address) {
                            localIP = address.getHostAddress();
                            break OK;
                        }
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
            ip =  localIP;
        }
        return ip;
    }

    //通过request获取ip
    public static String getIp() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServerName();
    }

    //通过request获取端口
    public static String getLocalPort() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServerPort() + "";
    }


    public static String getIpAndPort() {
        return  getLocalIP() + "#" + getLocalPort();
    }

}
