One, Java get server IP (go to: https://www.cnblogs.com/george93/p/6306579.html)
//method One, is also the simplest one. String server_ip =inetaddress.getlocalhost (). Gethostadress (). toString ();//Method Two:/*** Get server IP address *@return */@SuppressWarnings ("Unchecked") Public Staticstring Getserverip () {string Server_ip=NULL; Try{Enumeration Netinterfaces=networkinterface.getnetworkinterfaces (); InetAddress IP=NULL; while(Netinterfaces.hasmoreelements ()) {NetworkInterface ni=(NetworkInterface) netinterfaces.nextelement (); IP=(inetaddress) ni.getinetaddresses (). Nextelement (); Server_ip=ip.gethostaddress (); if(!ip.issitelocaladdress () &&!ip.isloopbackaddress ()&& ip.gethostaddress (). IndexOf (":") = =-1) {server_ip=ip.gethostaddress (); Break; } Else{IP=NULL; } } } Catch(SocketException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnserver_ip; }}
Second, Java get client IP (go to: http://www.cnblogs.com/ITtangtang/p/3927768.html)
Its core idea is to get through the servlet of HTTP;
//First Kind/*** Obtain client IP from Request object, handle HTTP proxy server and Nginx reverse proxy intercept IP *@paramRequest *@returnIP*/ Public Staticstring Getlocalip (HttpServletRequest request) {string Remoteaddr=request.getremoteaddr (); String forwarded= Request.getheader ("X-forwarded-for"); String Realip= Request.getheader ("X-real-ip"); String IP=NULL; if(Realip = =NULL) { if(Forwarded = =NULL) {IP=remoteaddr; } Else{IP= remoteaddr + "/" + Forwarded.split (",") [0]; } } Else { if(Realip.equals (forwarded)) {IP=Realip; } Else { if(Forwarded! =NULL) {Forwarded= Forwarded.split (",") [0]; } IP= Realip + "/" +forwarded; } } returnIP; }//The second Kind Public Staticstring GetIP (HttpServletRequest request) {string Remoteaddr=request.getremoteaddr (); String forwarded= Request.getheader ("X-forwarded-for"); String Realip= Request.getheader ("X-real-ip"); String IP=NULL; if(Realip = =NULL) { if(Forwarded = =NULL) {IP=remoteaddr; } Else{IP= remoteaddr + "/" +forwarded; } } Else { if(Realip.equals (forwarded)) {IP=Realip; } Else{IP= Realip + "/" + Forwarded.replaceall ("," + Realip, "" "); } } returnIP; }//The third and most clear and reasonable kind of Public Staticstring getIp2 (HttpServletRequest request) {string IP= Request.getheader ("X-forwarded-for"); if(Stringutils.isnotempty (IP) &&! " UnKnown ". Equalsignorecase (IP)) { //multiple reverse proxies will have more than one IP value, the first IP is the real IP intindex = Ip.indexof (","); if(Index! =-1){ returnIp.substring (0, index); }Else{ returnIP; }} IP= Request.getheader ("X-real-ip"); if(Stringutils.isnotempty (IP) &&! " UnKnown ". Equalsignorecase (IP)) { returnIP; } returnrequest.getremoteaddr (); }
Java get client IP and server IP