I've two machines: Server & Client
when I ask for the client ip in the client machine by
TcpClient client = new TcpClient();
client.Connect(serverip, PORTNO);
MessageBox.Show(client.Client.LocalEndPoint.ToString());
I get: 192.168.241.128:1025
It's the client ip.
but when I apply on the server the following:
_client = client;
_clientIP = client.Client.RemoteEndPoint.ToString();
AllClients.Add(_clientIP, this);
data = new byte[_client.ReceiveBufferSize];
_client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(_client.ReceiveBufferSize), ReceiveMessage, null);
MessageBox.Show(client.Client.RemoteEndPoint.ToString());
I get 192.168.92.1:1047
which is the server ip!
What's the problem?
That happend to me one day...
the problem is using vmware!
when I tried to connect to a real network...I got the correct IP's
Try to do it with a real network!
Related
I use dotnet core 3.1 and I need the IP address of my website visitors, but when I try to get it, the IP of the server is returned, not the client. Here is the code I use:
var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
This returns null. Then I tried to get my IP address using a third-party website. So I did this:
WebRequest request = WebRequest.Create("https://api.ipify.org/");
This will also return the IP address of the server, not the client. Then I tried this:
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
and this:
string localIP = string.Empty;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
but they return local IP addresses.
return localIP.ToString();
And some codes line HTTPContext.Current.Request.UserHostAddress or ServerVariables["REMOTE_ADDR"] are not valid in dotnet core.
Any suggestion, please?
I'm assuming that you are running the website not by directly exposing Kesterl to the end clients but under some reverse proxy (IIS/nginx). In that case for Connection.RemoteIpAddress to work property you have to configure the application by adding something like following code in the startup:
app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor })
I'm coding a system with server (behind NAT with UDP port forwarding, static white IP) and client (behind NAT without any custom settings).
The task is sending datas from server to client via Internet .
In order to Server knows client's endpoint (and client's router keeps translation table), Client sends every 5 second easy UDP request to Server like "Hello!".
Server code:
private void SendData(ref string destination, CancellationToken cancelToken)
{
UdpClient senderClient = new UdpClient(AddressFamily.InterNetwork);
try
{
while (true)
{
cancelToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(destination))
continue;
byte[] testMessage = Encoding.UTF8.GetBytes("AnyDatas");
string ip = destination.Split(':')[0];
string p = destination.Split(':')[1];
IPEndPoint clientEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(p));
senderClient.Send(testMessage, testMessage.Length, clientEP);
Thread.Sleep(3000);
}
}
catch (OperationCanceledException ex)
{ }
finally
{
if (senderClient != null)
senderClient.Close();
}
}
private void ListenConnectionSupport(ref string stClientEP, CancellationToken cancelToken)
{
IPEndPoint IpEp = new IPEndPoint(IPAddress.Any, 13001);
UdpClient listenClient = new UdpClient(IpEp);
try
{
while (true)
{
cancelToken.ThrowIfCancellationRequested();
IPEndPoint cIpEp=null;
byte[] messageBytes = listenClient.Receive(ref cIpEp);
if (Encoding.UTF8.GetString(messageBytes) == "UDP-support")
{
stClientEP = String.Format("{0}:{1}",cIpEp.Address,cIpEp.Port);
}
}
}
catch (OperationCanceledException ex)
{ }
finally
{
if (listenClient != null)
listenClient.Close();
}
}
And that works even!
But only if client under the same router, despite on sending client->server request to external server IP.
I use my smartphone like client's router and try again (client is another PC). But although server gets Hello-request and sends answer, however client gets nothing.
UPDATE-----------------
I need to develop system for scheme:
Server (192.168.0.3)-routerA (static public IP, has port forwarding for server)- INTERNET- routerB(any regular hotspot or router) - Client
Algorithm:
Client sends to routerA (in this context routerA=Server) "Hello, give me your data." For router table client sends this continusly.
Server from previous message (like STUN server) can note Client EP.
Server in WHILE(true) cycle sends datas to Client.
The error is "Client doesnt get data from server".
If that is matters
server listen 13001 port, Client knows this port number
In "one router case" case server see client's endpoint like "192.168.0.5" (his local IP) and in "two routers" case, client's endpoint looks like unknown IP (I dont know what is that, his ipconfig shows another).
Please, show me proper direction!
I have write a ssl server/client program:
server:
static void Main(string[] args)
{
var store = new X509Store(StoreName.Root);
store.Open(OpenFlags.ReadWrite);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "TestServer", false);
var x509 = certs[0];
var listener = new TcpListener(IPAddress.Parse("192.168.97.2"), 2000);
listener.Start();
while (true)
{
var client = listener.AcceptTcpClient();
var sslStream = new SslStream(client.GetStream(), false);
sslStream.AuthenticateAsServer(x509, false, SslProtocols.Tls, true);
Console.WriteLine(ReadMessage(sslStream));
}
}
client:
static void Main(string[] args)
{
var client = new TcpClient("192.168.97.2",2000);
var ssl = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
ssl.AuthenticateAsClient("TestServer");
byte[] message = Encoding.UTF8.GetBytes("abc");
ssl.Write(message);
ssl.Flush();
client.Close();
}
it work's fine,but when I try to capture network packages by wireshark,I got TCP package between server and client.
I think I should got TLS package,I don't know why.
SSL handshake is in application layer not TCP/IP layer
and as you know wireshark monitors TCP/IP layer, So you can see Tcp process of handshake with some ambiguous data because it is encrypted with SSL public or private key.
So you can not monitor exact SSL handshake process with Wireshark(Although I work so many time with SSL I can not find any tools for monitoring exactly ssl handshake process).
good luck.
i had created dynamic endpoint in server side and that endpoint used by client side.
Server side Code:
for (int i = 1; i <= 3; i++)
{
host.AddServiceEndpoint(typeof(PokerService.IPlayerService),
new NetTcpBinding(),
#"net.tcp://localhost:5054/player" + i);
}
Client side:
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Message);
binding.Name = "NetTcpBinding_IPlayerService";
binding.Security.Message.ClientCredentialType = MessageCredentialType.IssuedToken;
EndpointAddress myEndpointAdd = new EndpointAddress(new Uri("net.tcp://localhost:5054/player1"),
EndpointIdentity.CreateDnsIdentity("pident.cloudapp.net"));
var PlayerChannelFactory = new DuplexChannelFactory<ClientApplication.PlayerService.IPlayerService>(new PlayerHandler(handler, this), binding, myEndpointAdd);
but it give error in this following line :
Player loggedIn = PlayerServiceProxy.Login("testuser" + Guid.NewGuid().ToString());
The error is:
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9870000'."
have anyone idea?
It seems like timeout. Review your client and service timeouts configuration.
Also, try to use svcTraceViewer.exe to review wcf trace
I'm trying to build a C# SignalR app (console app on the server, winforms app on the client), and it works great (in Visual Studio) when both the client and server are on the same PC, but when I deploy the server and repoint the client to the server, I'm getting a "407 Proxy Authentication Required" exception when it tries to start.
This is my code...
var _connection = new HubConnection("http://www.redacted.com:8088/");
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
I noticed that HubConnection has a Credentials property, and so I figured I'd try replacating some code I've used with WebServices when dealing with proxies (shown below, where I just make an HTTP request out and then pick up the proxy settings and credentials from that), but I get the same exception.
var _connection = new HubConnection("http://www.redacted.com:8088/");
var req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
var proxy = new WebProxy(req.Proxy.GetProxy(req.RequestUri).AbsoluteUri) {UseDefaultCredentials = true};
_connection.Credentials = proxy.Credentials;
var _hub = _connection.CreateProxy("MyHub");
_connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
MessageBox.Show(string.Format("Could not connect - {0}", task.Exception.ToString()));
}).Wait();
This is required for some work I'm doing for a client where they want their local PCs to be able to receive messages from a remote system that's hosted outside the company.
Thanks!
Try to set the DefaultWebProxy:
WebProxy wproxy = new WebProxy("new proxy",true);
wproxy.Credentials = new NetworkCredential("user", "pass");
WebRequest.DefaultWebProxy = wproxy;