How do you get the source domain using HttpServletRequest?
Source domain is the requester's domain.
Thanks.
You could do either
// gets client (browser)'s hostname
String host = request.getRemoteHost();
OR
// get the server's domain name.
String domain = new URL(request.getRequestURL().toString()).getHost();
To get the source domain you can use request.getHeader("origin")
especially if the requests have to pass through a proxy server.
Hostname request
InetAddress ip = InetAddress.getLocalHost();
String hostname = ip.getHostName();
out.print("Your current IP address : " + ip+"\n");
out.print("Your current Hostname : " + hostname);
Related
I need to populate a database with the fields of the HTTP requests based on if the sender IP is valid or not.
For example if someone make a GET request on my IP with that:
/test/demo.php?name1=value1&name2=value2
How can I receive it so I can handle it and perform actions like:
Get the ip of the sender (And validate it - just confronting it with a list -)
Recognize the type of the Request
Extrapolate the fields (value1 and value2) and save them in variables
I'm using java.net.http package
You can't perform that using package java.net.http because you need to create an http server not an http client. To achieve that, you need HttpServer which is found in package com.sun.net.httpserver.
The first thing is to create a new instance of HttpServer :
final int port = 3000;//You can change with your port number you need
final HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("Listening port : " + port);
Then, configure an http context. The first parameter accepts the route you defines and the second parameter accepts the http handler in which you can extract all your data that you need to store in your database.
httpServer.createContext("/test/demo.php", buildHttpHandler());//buildHttpHandler is to create
What contains the function buildHttpHandler()? :
Each time where route /test/demo.php is called, the content of arrow function is called. Here, we attempt only to create a simple page html and serves it to the http client. But before responding http client, we need to extract all data you need (ip, request type and parameters).
return httpExchange -> {
final String html = "<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <title>Page</title>\n" +
" <meta charset='utf-8'/>\n" +
" </head>\n" +
" <body>Ok</body>\n" +
"</html>";
//Function to create
extractData(httpExchange);
httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
httpExchange.sendResponseHeaders(200, html.length());
final OutputStream outputStream = httpExchange.getResponseBody();
outputStream.write(html.getBytes(StandardCharsets.UTF_8));
outputStream.close();
};
What contains extractData() function?
In this function we will extract the data you need.
final String ip = getClientIp(httpExchange);
System.out.println("IP : " + ip);
final String requestType = httpExchange.getRequestMethod();
System.out.println("Request type : " + requestType);
final Map<String, String> parameters = extractParameters(httpExchange);
displayParameters(parameters);
Extracting ip client is more complicated because sometime client uses proxy that's why we create a dedicated function getClientIp() to extract the ip.
In this function, we attempt to extract firstly proxy ip. If not found, we extract standard ip from remote :
final String ip = getProxyIp(httpExchange);
return ip == null ? httpExchange.getRemoteAddress().getAddress().getHostAddress() : ip;
To extract proxy ip, we create another function getProxyIp(). It attempts to extract the ip provided from x-forwarded-for request header.
final List<String> ips = httpExchange.getRequestHeaders().get("x-forwarded-for");
return ips == null ? null : ips.get(ips.size() - 1);
I don't know what do you mean with extrapolating fields but you can store all data in a Map variable. The key will be the name of parameter and the value will be the value of parameter. But this is complicated also because we need to parse the string value from name1=value1&name2=value2. So, we create a new function extractParameters(). It contains :
final String query = httpExchange.getRequestURI().getQuery();
final Map<String, String> parameters = new HashMap<>();
if (query != null) {
final String[] firstParts = query.split("&");
for (final String firstPart : firstParts) {
final String[] secondParts = firstPart.split("=");
final String name = secondParts[0];
final String value = secondParts.length > 1 ? secondParts[1] : null;
parameters.put(name, value);
}
}
return parameters;
You notice maybe what is displayParameters() content. It just attempts to display, parameters retrieved from extractParameters().
for (final Map.Entry<String, String> parameter : parameters.entrySet()) {
System.out.println("Parameter key : " + parameter.getKey());
System.out.println("Parameter value : " + parameter.getValue());
}
And finally don't forget to start the http server :
httpServer.start();
You can check for a full code here https://gist.github.com/razafinarivohanania/24fe0986ea5868097404f2a758131823
When you test it, you can get something like :
IP : 127.0.0.1
Request type : GET
Parameter key : name2
Parameter value : value2
Parameter key : name1
Parameter value : value1
I have a Spring (Java) website that uses Kemp Technologies' LoadMaster as the balancer, which sits before my web servers.
I am able to get the right IP address of a visitor at any page via:
request.getRemoteAddr()
However, I am not able to get the correct domain of the referrer. Here is what I did:
I have the following code in a HandlerInterceptorAdapter, which is called for each web request. The code is to check whether a particular session variable exists. If yes, no action. If no, record the referrer's domain in session.
HttpSession session = request.getSession();
String value = (String) session.getAttribute("referrer");
if (value == null) {
String scheme = request.getScheme();
String serverName = request.getServerName();
int portNumber = request.getServerPort();
String url = scheme +"://"+serverName+ (portNumber == 80? "": portNumber);
session.setAttribute("referrer", url);
}
In other pages when I need the referrer's domain, I have the following:
String value = (String) request.getSession().getAttribute("referrer");
The problem is that the value I got is always my own domain (ex. http://www.example.com).
Where have I gone wrong?
I have a question about java web applications.
Is there a way to map url: index.jsp?lng=en to: index/en?
Take the host name from the request object if you are getting HttpServletRequest OR you can use regex to get the host name. en is a request parameter value which you can get using request.getParameter("lng")
URL aURL = new URL("index.jsp?lng=en");
System.out.println("hostname = " + aURL.getHost()); //index
then return String with hostName + "/" + paramValue
So I am trying to use jmdns on Android 3.2.1 (HTC Flyer) and I am using jmdns for service discovery. Everything works nicely except that one of my three devices (rest of them work fine) is broadcasting IPv6 address instead of IPv4. This is very weird as they are all connected to my home network over DHCP so they are all assigned IPv4 address.
So on my device I run
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
multicastLock = wifi.createMulticastLock("mylockthereturn");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
try {
jmdns = JmDNS.create();
jmdns.registerServiceType(jmdnsType);
String jmdnsName = /* Read from db */;
serviceInfo = ServiceInfo.create(jmdnsType, huggler_id, server.getLocalPort(), " blah blah");
jmdns.registerService(serviceInfo);
Log.d(TAG, "JMDNS service registered on ip " + jmdns.getInterface());
} catch (IOException e) {
Log.e(TAG, "Error creating JMDNS service (" + e.getMessage() + ")");
e.printStackTrace();
}
And it prints out nice IPv4 IP which actually matches the one assigned by my network (success).
But when I run code which discovers services on other devices.
for(ServiceInfo si : jmdns.list(jmdnsType, 6000)) { // timeout: 6s
if (si.getName().equals(jmdnsNAme))
continue;
try {
Log.d(TAG, "Host has " + si.getInet4Addresses().length + " v4 addresses. ");
Log.d(TAG, "Host has " + si.getInet6Addresses().length + " v6 addresses. ");
}
And when it discovers Flyer it shows exactly one v6 address.
Can anybody suggest what might have happened?
I am using Jmdns 3.4.0 (3.4.1 does not work at all!) and I am kind of a zeroconf newbie.
UPDATE:
Some new information:
D/Huggler ( 5691): Host has 0 v4 addresses.
D/Huggler ( 5691): Host has 1 v6 addresses.
D/Huggler ( 5691): Host IPv6 address is fe80::66a7:69ff:feeb:9083
D/Huggler ( 5691): Host IPv6 hostname is fe80::66a7:69ff:feeb:9083
D/Huggler ( 5691): Host is linklocal true
Can anybody help interpret those?
Was seeing the same problem, but passing in the InetAddress in the call to jmDNS.create seemed to do the trick.
So try something like:
WifiManager wifi = (WifiManager)getActivity().getSystemService(android.content.Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wifi.getConnectionInfo().getIpAddress());
jmdns = JmDNS.create(InetAddress.getByName(ip));
I need to create TQL queries to query out sets of data from the UCMDB.
I am having 2 problems:
1) How can I find relationships which exists between CIs ( i do not have administrative privileges so need to do it in code somehow)
I need this to get required data.
2) I have created the following query: But I keep getting the IP property value as null.
I checked that IP has an attribute called ip_address.
Code:
import com.hp.ucmdb.api.types.TopologyRelation;
public class Main {
public static void main(String[] args)throws Exception {
final String HOST_NAME = "192.168.159.132";
final int PORT = 8080;
UcmdbServiceProvider provider = UcmdbServiceFactory.getServiceProvider(HOST_NAME, PORT);
final String USERNAME = "username";
final String PASSWORD = "password";
Credentials credentials = provider.createCredentials(USERNAME, PASSWORD);
ClientContext clientContext = provider.createClientContext("Test");
UcmdbService ucmdbService = provider.connect(credentials, clientContext);
TopologyQueryService queryService = ucmdbService.getTopologyQueryService();
Topology topology = queryService.executeNamedQuery("Host IP");
Collection<TopologyCI> hosts = topology.getAllCIs();
for (TopologyCI host : hosts) {
for (TopologyRelation relation : host.getOutgoingRelations()) {
System.out.print("Host " + host.getPropertyValue("display_label"));
System.out.println (" has IP " + relation.getEnd2CI().getPropertyValue("ip_address"));
}
}
}
In the above query output: I get the host names with IP = null
I have a sample query in JYthon which I am unable to figure out: Its for the above code only.
Attaching it for anyone who can understand it.
import sys
UCMDB_API="c:/ucmdb/api/ucmdb-api.jar"
sys.path.append(UCMDB_API)
from com.hp.ucmdb.api import *
# 0) Connection settings
HOST_NAME="192.168.159.132"
PORT=8080
USERNAME="username"
PASSWORD="password"
# 1) Get a Service Provider from the UcmdbServiceFactory
provider = UcmdbServiceFactory.getServiceProvider(HOST_NAME, PORT)
# 2) Setup credentials to log in
credentials = provider.createCredentials(USERNAME, PASSWORD)
# 3) Create a client context
clientContext = provider.createClientContext("TESTING")
# 4) Connect and retrieve a UcmdbService object
ucmdbService = provider.connect(credentials, clientContext)
# 5) Get the TopologyQueryService from the UcmdbService
queryService = ucmdbService.getTopologyQueryService()
# ======= Everything After this is specific to the query =======
# 6) Execute a Named Query and get the Topology
topology = queryService.executeNamedQuery('Host IP')
# 7) Get the hosts
hosts = topology.getAllCIs()
# 8) Print the hosts and IPs
host_ip = {}
for host in hosts:
host_name = host.getPropertyValue("display_label")
if host_name in host_ip.keys():
ips = host_ip[host_name]
else:
ips = {}
host_ip[host_name] = ips
for relation in host.getOutgoingRelations():
ip_address = relation.getEnd2CI().getPropertyValue("display_label")
if ip_address in ips.keys():
pass
else:
ips[ip_address] = ''
print "%s , %s" % (host_name, ip_address)
Please help.
I am unable to understand how to go about this further.
Thank you.
The easiest fix would be use the display_label property from the IP address CI instead of the ip_address property. The Jython reference code uses display_label for its logic.
I'd be a little concerned about using display_label since the display_label formatting logic could be changed to no display the IP address for IP CIs. Getting data directly from the ip_address property is a better choice and should work if the TQL is defined to return that data. Check the Host IP TQL and ensure that it's configured to return ip_address for IP CIs.