Use SignalR with IP Address instead of computer name - c#

I have a SignalR service setup to run self hosted in a Windows Service.
When I enter this address:
http://mycomputer.mydomain.net:8789/signalr/signalr/negotiate
I get some xml (for negotiation) displayed in the browser (showing that hit the service correctly.)
But if I enter this address (that has mycomputer.mydomain.net's ip address in place of the computer name):
http://10.92.15.6:8789/signalr/signalr/negotiate
or this
http://localhost:8789/signalr/signalr/negotiate
I get this error:
Bad Request - Invalid Hostname
HTTP Error 400. The request hostname is invalid.
I have tried also using:
http://10.92.15.6.mydomain.net:8789/signalr/signalr/negotiate
But I just get:
This site can’t be reached
10.92.15.6.mydomain.net’s server DNS address could not be found.
Is there someway to be able to make SignalR work using an IP Address instead of the computer name?

I had to change my startup from this:
string url = "http://" + machineName + ".mydomain.net:8789";
server = WebApp.Start<Startup>(url);
to this:
string url = "http://*:8789";
var startOptions = new StartOptions(url);
server = WebApp.Start<Startup>(startOptions);

Related

How do I obtain Client IP address in .net-core instead of the load balancers? (using X-Forwarded-For)

I'm simply trying to get the Client IP address in a .net-core controller after they POST. We have a load balancer between the client and the server.
The setup in my startup:
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
And configure:
app.UseForwardedHeaders();
Then I attempt to call the code below, but it returns the load balancer IP address, not the clients IP:
var clientIpAddress = HttpContext.Connection.RemoteIpAddress.ToString();
I have tried everything I can search on this website and the documentation, and nothing seems to work. I've also tried using HttpContext.Request.Headers["X-Forwarded-For"]
which returns null / empty.
Our OPS team says the IP isn't being modified by the balancer, and should be in the value of the x-Forwarded-For header. Why is the load balancer sending back it's IP and not the clients IP address?
You can try this method to get client IP address:
1.Add the Microsoft.AspNet.HttpOverrides package.
2.n your configure() method add below code.
app.UseOverrideHeaders(new OverrideHeaderMiddlewareOptions
{
ForwardedOptions = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
Your settings for the Middlewares are correct and I am also having the same settings.
Same issue we have just faced. We can't get the values in headers for header "X-Forwarded-For" even in controller. After deployment all were gone hanged up and 500 error were there. So I have done one illegal code you can say in _Layout.cshtml and you know in this client side file I can read the headers like X-Forwarded-For,X-Azure-ClientIP and X-Azure-SocketIP. And all can have only one ip address and that is of client's public ip address. And after getting the ip address from Layout page you can store that value in session and redirect to any other page and from that page you can use ip address from session. Below is the code in layout to read the headers.
if (string.IsNullOrEmpty(HttpContextAccessor.HttpContext.Session.GetString("ClientIpAddress")))
{
Microsoft.Extensions.Primitives.StringValues headerIPAddress = string.Empty;
HttpContextAccessor.HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out headerIPAddress);
HttpContextAccessor.HttpContext.Session.SetString("ClientIpAddress", headerIPAddress.ToString());
HttpContextAccessor.HttpContext.Response.Redirect("~/Home/Index");
}
In X-Forwarded-For you will get client ip,proxy1 & proxy2.
Get the first item of the client/user IP, The first item is the original client IP
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new
char[] { ',' }).FirstOrDefault()

How can I get recipient ip address and location when Recipient opens my mail?

How can I get client ip and address when client open my mail? I tried this:
var ip = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
IpInfo ipInfo = new IpInfo();
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
obj.country = myRI1.EnglishName;
obj.countryCode = myRI1.ThreeLetterISORegionName;
obj.state = ipInfo.Region;
obj.city = ipInfo.City;
obj.ip = ipInfo.Ip;
But this returns my host server Address
If this code lives in a web service, you may be having an issue in which your application is creating a proxy between itself and your service instead of directly connecting it to the browser.
[Browser] ---> [ASP.NET App / Proxy] ---> [Web Service]
This would explain why the service is always seeing your server's IP address as the client because, from the web service point of view, the ASP.NET application IS it's "client".
In this case, the you would need to collect the client IP address at the application layer and pass it to the web service.
Collect IP Address Here
|
V
[Browser] ---> [ASP.NET App / Proxy] ---> [Web Service]
^
|
Pass IP to web Service

Set Custom Host Name as part of changing the Endpoint Address of a Soap Client

I am presently in a scenario where I need to have multiple servers that live behind a Load Balancer talk to each other directly, and I need to communicate with specific servers for PUSH notifications. This is for a chat tool that requires users that have been moved to different servers by a load balancer to still be able to talk to one another live.
The actual pushes are being handled with Signal-R, and I have all of that working. So here is the actual complication:
Normally, this would be simple enough to do by targeting them via IP Address to bypass the load balancer. However, this is complicated because the servers expects a specific Host name or it will reject the request.
I know it is possible to do this with a WebRequest, but would like to avoid having to build a proxy if I can help it.
Here is the piece I have where I'm trying to send a global push to tell everyone across all connected servers to update their buddy lists because someone logged in or out.
private void NotifyUsersChangedGlobal()
{
List<string> addressesToNotify = ChatUsers.Select(x => x.ServerIP).Distinct().ToList();
foreach (string address in addressesToNotify)
{
ChatUplinkSoapClient client = BuildClient(address);
client.NotifyUsersChanged();
}
}
And this is the Client Builder where (I assume) I need to handle assigning the custom Host name to ride on top of the IP Address
private ChatUplinkSoapClient BuildClient(string endpointIP)
{
string relativeUrl = "/WebServices/ChatUplink.asmx";
//Turn on HTTPS
HttpBindingBase binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
//Link together the IP Address and the asmx route
EndpointAddress endpoint = new EndpointAddress(endpointIP + relativeUrl);
//Make the Client
ChatUplinkSoapClient client = new ChatUplinkSoapClient(binding, endpoint);
//Need to set Host header to "HostHeaderName", or the server will reject the request.
return client;
}
Ideas?

Url works when pinging but causes UriFormatException

I have a mail server I'm trying to connect to with exchange web services. If I ping the server, it works, but it gets a UriFormatException when provided in code.
Urls that work in command prompt but fail in c#
myserver.mydomain.com
myserver
192.168.100.1 (my server's ip)
Urls that can be parsed into URIs but fail to be pinged
http://myserver.mydomain.com
http://192.168.100.1
I also tried adding \\ to the beginning but had no luck.
We do have a bit of a weird setup with connecting to our domain when on-network that I believe is what is causing http://myserver.mydomain.com to fail in ping. How can I turn the base url (without the http://) into a string that will be valid for a c# Uri?
Code:
var serverUrl = "myserver.mydomain.com"; //base string I'd like to use
_exchange.Url = new Uri(serverUrl); //causes UriFormatException: Invalid URI: The format of the URI could not be determined.
To consturct Uri from host name use UriBuilder:
var builder = new UriBuilder();
builder.Host = "myserver.mydomain.com";
var uri = builder.Uri;
Note that what you call "uri" (myserver.mydomain.com) is actually "host name" or "DNS name" which is what get resolved to IP and than used to Ping. "http://myserver.mydomain.com" is absolute Uri for particular protocol (HTTP).

how to find the ip address of client who is login to our website or browsing our website

Here i have a small problem, that i want to find out the IP Address of the client who is accessing my website, i tried so many but all these are giving me 127.0.0.1 as IP, while i am testing in local host,
Please some one provide the code snippet and help me,
Thanks in advance,
public string GetClientIP()
{
string result = string.Empty;
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
result = ipRange[0];
}
else
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return result;
}
This is to be expected, your localhost IP address will most of the time be 127.0.0.1.
As said in the comments, when you will deploy your site and remote clients access it, their actual IP will correctly be retrieved.
If you want to try locally, you can try to configure your local network so that a remote computer on the same network access your web site. There you should see the IP address of that computer (for instance: 192.168.x.x).

Categories