java - Getting IP address of client -
i developing web application using jsp, servlets (container: glassfish) in need clients ip address
.
i getting clients ip address, because want give access pages (like customer maintenance forms) on computers withing office, want restrict access pages outside office.
following code far:
way1
string ipaddress = request.getremoteaddr(); system.out.println("ip address: "+ipaddress);
way2
string ipaddress=null; string getway = request.getheader("via"); // gateway ipaddress = request.getheader("x-forwarded-for"); // proxy if(ipaddress==null) { ipaddress = request.getremoteaddr(); } system.out.println("ip address: "+ipaddress);
above code gives me different ip address
each time when restart computer (shutdown->start or restart).
i getting ip6
like:
fe80:0:0:0:20ca:1776:f5ff:ff15%13
let me know wrong code?
as @martin , this answer explained, complicated. there no bullet-proof way of getting client's ip address.
the best can try parse "x-forwarded-for"
, rely on request.getremoteaddr();
public static string getclientipaddress(httpservletrequest request) { string xforwardedforheader = request.getheader("x-forwarded-for"); if (xforwardedforheader == null) { return request.getremoteaddr(); } else { // of https://en.wikipedia.org/wiki/x-forwarded-for // general format of field is: x-forwarded-for: client, proxy1, proxy2 ... // want client return new stringtokenizer(xforwardedforheader, ",").nexttoken().trim(); } }
Comments
Post a Comment