Not getting IP address of Client in Java Spring Web Application - apache

I have a java Spring web application, deployed on an Apache server, in which I wish to capture IP address of client using the following code.
public static String getIpFromRequest(HttpServletRequest request){
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || "".equals(remoteAddr)) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}
By this code I'm getting the same IP address for every client. I have referred all stackoverflow questions, but they suggested same above code. Please suggest possible way.

Related

Fail to connect to WCF Service on my Localhost

I got the below error when trying to connect to WCF service running on my localhost using the WCF Test Client tool. I entered the end-point address as "net.tcp://localhost:19998/MyWCFService". MyWCFService is launched within Visual Studio 2017 on my local PC.
"There was no endpoint listening at net.tcp://localhost:19998/MyWCFService that
could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
I can verify the port 19998 is listening on my PC using the netstat.
TCP 0.0.0.0:19998 LISTENING
I have disabled all the firewall on my PC.
It turns out that my WCF service has some runtime errors that prohibits any clients to connect to it.. I have fixed the errors and i can connect now. Thanks.
It seems that the error is caused by that the service address is wrong. How do you host the service on the server side? I would like you could post more details about the server side so that give you an effective reply.
Here is my example about using NetTCPBinding, wish it is useful to you.
Server
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("net.tcp://localhost:1500");
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
using (ServiceHost sh = new ServiceHost(typeof(Calculator), uri))
{
sh.AddServiceEndpoint(typeof(ICalculator), binding,"");
ServiceMetadataBehavior smb;
smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb = new ServiceMetadataBehavior();
//smb.HttpGetEnabled = true;
sh.Description.Behaviors.Add(smb);
}
Binding mexbinding = MetadataExchangeBindings.CreateMexTcpBinding();
sh.AddServiceEndpoint(typeof(IMetadataExchange), mexbinding, "MEX");
sh.Open();
Console.Write("Service is ready....");
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface ICalculator
{
[OperationContract]
int Test(int a);
}
public class Calculator : ICalculator
{
public int Test(int a)
{
return a * 2;
}
}
Result.
Feel free to let me know if there is anything I can help with.

azure sql server firewall settings

How to find my computer's external IP address for azure sql server firewall settings? It is different from the one I get from Ipconfig command(IPv4). I can see a specific IP address on the azure portal but want to know if/how I can see it from my machine?
There is a "AutoDetectClientIP" Management API call that updates an existing Firewall Exception to the caller's IP address.
But you need access to a Management Certificate that is valid for the given subscription, the subscription ID, the name of the SQL Azure Server and the name of the Firewall Exception.
Below how you can use that API.
public static bool SetFirewallRuleAutoDetect(string certFilename, string certPassword, string subscriptionId, string serverName, string ruleName)
{
try
{
string url = string.Format("https://management.database.windows.net:8443/{0}/servers/{1}/firewallrules/{2}?op=AutoDetectClientIP",
subscriptionId,
serverName,
ruleName);
HttpWebRequest webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
webRequest.ClientCertificates.Add(new X509Certificate2(certFilename, certPassword));
webRequest.Method = "POST";
webRequest.Headers["x-ms-version"] = "1.0";
webRequest.ContentLength = 0;
// call the management api
// there is no information contained in the response, it only needs to work
using (WebResponse response = webRequest.GetResponse())
using (Stream stream = webResponse.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
Console.WriteLine(sr.ReadToEnd());
}
// the firewall was successfully updated
return true;
}
catch
{
// there was an error and the firewall possibly not updated
return false;
}
}
Above information comes from here.

Apache Axis2 Webservice- getting port and ip address of client

I have a Apache Axis2 web service and Im trying to log client ip address and port number. Im able to get the ip address using:
MessageContext inMessageContext = MessageContext.getCurrentMessageContext();
String ip = (String)inMessageContext.getProperty("REMOTE_ADDR");
How can i obtain the port number it came from?
I am newbie for axis2, I cant understand your question. Are you trying to access requester port number or requesting URL port number...?
May be below link useful for you to getting requesting URL port number. Please check
public class MyServlet extends AxisServlet
{
protected MessageContext createMessageContext( HttpServletRequest request, HttpServletResponse response, boolean invocationType ) throws IOException
{
MessageContext mc = super.createMessageContext( request, response, invocationType );
URL url = new URL( request.getRequestURL().toString() );
mc.setProperty( "myPort", url.getPort() );
return mc;
}
}
Of course you must put your class name in axis2/.../web.xml and restart tomcat. Then you can check port number inside any axis2 invocation:
MessageContext mc = MessageContext.getCurrentMessageContext();
int port = ( Integer ) mc.getProperty( "myPort" );
source : How to detect which transportReceiver is used in Axis2

Redirect HTTP to HTTPS in MVC4 Mobile Application

In My MVC4 Mobile application i have registration, login page and remaining pages. i would like to redirect user to HTTPS connection for all sensitive information pages like registration and login pages and HTTP to remailing pages.
I prefer you to use conditional functionality putting the class
public class RequireHttpsConditional : RequireHttpsAttribute
{
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
var useSslConfig = ConfigurationManager.AppSettings["UseSSL"];
if (useSslConfig != null)
{
if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("The requested resource can only be accessed via SSL.");
}
var request = filterContext.HttpContext.Request;
string url = null;
int sslPort;
if (Int32.TryParse(useSslConfig, out sslPort) && sslPort > 0)
{
url = "https://" + request.Url.Host + request.RawUrl;
if (sslPort != 443)
{
var builder = new UriBuilder(url) { Port = sslPort };
url = builder.Uri.ToString();
}
}
if (sslPort != request.Url.Port)
{
filterContext.Result = new RedirectResult(url);
}
}
}
}
and using this [RequireHttpsConditional] above the action result.
i have got this code somewhere in internet and is working fine for me.
in web.config appsettings use <add key="UseSSL" value="443" />
and in the controller above the action result you need put
[RequireHttpsConditional]
public ActionResult SignIn()
{
}
In IIS where you have your project right click and click "Edit Bindings" then you add a custom type https and port no 443 (you can change it)
Note this will work only in production environment. when executed locally it wont be working.
When you execute it locally you have request.Url.Host which will return you only localhost and missing your port number. so if you use it in MVC you will find error loading page for your pages where you put this code.
So this will work when you have the host assigned instead of using the localhost with a specific port number.
Within the controller actions that you wish to be HTTPS add the following code to the top of the method (of course you can simply add this to its own method and then call it):
if (!HttpContext.Request.IsSecureConnection)
{
var url = new UriBuilder(HttpContext.Request.Url);
url.Scheme = "https";
Response.Redirect(url.Uri.AbsoluteUri);
}
It is recommended though that you keep HTTPS on throughout your site to protect against a MITM attack against the auth cookie.

Cross domain policy file over net.tcp for WCF servicehost and Silverlight 5

I have a locally hosted WCF service and a silverlight 5 app that communicates with it. By default silverlight tries to obtain the cross domain policy file over HTTP when making calls to the WCF service. I need to change this so that the policy file is served over net.tcp port 943 instead.
I have setup a local tcp listener that serves up the policy file over port 943 and i have followed this technique whereby i make a dummy socket connection in order to obtain the policy file over tcp as it is only retrieved once per application lifetime. The tcp server is being hit as expected and i am getting SocketError property value as Success (though i must note, the first time i hit the tcp server after starting the listener, the result is always access denied).
From what i can tell, the policy file is either invalid as the silverlight application as still unable to connect or the above mentioned technique does not work with silverlight 5.
What i would like to know is if what i am doing is possible & im doing it correctly, otherwise if there is an alternative means to have the policy file successfully downloaded over tcp and removing the need for retrieving it over HTTP.
Thanks
I wrote a long post about hosting silverlight in WPF - and using WCF with a http listener here:
How can I host a Silverlight 4 application in a WPF 4 application?
Now while not directly answering your question, it does show how to create a http version of the policy file.
I have also written something that serves up a policy listener over port 943, but I can't find where I posted the source - so I'll keep digging. As far as I remember though, silverlight does a cascade find of the policy file, if it doesn't get a connection on port 80, it'll then look on port 943.
I hope this is of some help somewhere.
Ok, here is the policy listener I had for net.TCP transport i.e. not HTTP based. I presume you have sorted this by now, sorry for the delay. It may well be of use to someone else now.
I was looking for the MS thing that said they cascade from HTTP to TCP, however, I can't, and therefore have to assume it was bunk and then changed.
Either way, if you call using a net.TCP service, and want a listener for it, this code should help:
#region "Policy Listener"
// This is a simple policy listener
// that provides the cross domain policy file for silverlight applications
// this provides them with a network access policy
public class SocketPolicyListener
{
private TcpListener listener = null;
private TcpClient Client = null;
byte[] Data;
private NetworkStream netStream = null;
private string listenaddress = "";
// This could be read from a file on the disk, but for now, this gives the silverlight application
// the ability to access any domain, and all the silverlight ports 4502-4534
string policyfile = "<?xml version='1.0' encoding='utf-8'?><access-policy><cross-domain-access><policy><allow-from><domain uri='*' /></allow-from><grant-to><socket-resource port='4502-4534' protocol='tcp' /></grant-to></policy></cross-domain-access></access-policy>";
// the request that we're expecting from the client
private string _policyRequestString = "<policy-file-request/>";
// Listen for our clients to connect
public void Listen(string ListenIPAddress)
{
listenaddress = ListenIPAddress;
if (listener == null)
{
listener = new TcpListener(IPAddress.Parse(ListenIPAddress), 943);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger,lo);
}
listener.Start();
WaitForClientConnect();
}
private void WaitForClientConnect()
{
listener.BeginAcceptTcpClient(new AsyncCallback(OnClientConnected), listener);
}
public void StopPolicyListener()
{
if (Client.Connected)
{
// Should never reach this point, as clients
// are closed if they request the policy
// only clients that open the connection and
// do not submit a policy request will remain unclosed
Client.Close();
}
listener.Stop();
}
public void RestartPolicyListener()
{
listener.Start();
}
// When a client connects:
private void OnClientConnected(IAsyncResult ar)
{
if (ar.IsCompleted)
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;
// End the operation and display the received data on
// the console.
Client = listener.EndAcceptTcpClient(ar);
// Try and stop our clients from lingering, keeping the socket open:
LingerOption lo = new LingerOption(true, 1);
Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Set our receive callback
Data = new byte[1024];
netStream = Client.GetStream();
netStream.BeginRead(Data, 0, 1024, ReceiveMessage, null);
}
WaitForClientConnect();
}
// Read from clients.
public void ReceiveMessage(IAsyncResult ar)
{
int bufferLength;
try
{
bufferLength = Client.GetStream().EndRead(ar);
// Receive the message from client side.
string messageReceived = Encoding.ASCII.GetString(Data, 0, bufferLength);
if (messageReceived == _policyRequestString)
{
// Send our policy file, as it's been requested
SendMessage(policyfile);
// Have to close the connection or the
// silverlight client will wait around.
Client.Close();
}
else
{
// Continue reading from client.
Client.GetStream().BeginRead(Data, 0, Data.Length, ReceiveMessage, null);
}
}
catch (Exception ex)
{
throw new Exception(Client.Client.RemoteEndPoint.ToString() + " is disconnected.");
}
}
// Send the message.
public void SendMessage(string message)
{
try
{
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
//Client.Client.Send(bytesToSend,SocketFlags.None);
Client.GetStream().Write(bytesToSend,0, bytesToSend.Length);
Client.GetStream().Flush();
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion