I'm trying to create a request with IP address SAN. This is the function that is responsible for creating the CAlternativeName:
public static CAlternativeNameClass GetCurrentIpName() {
//get current machine IP address
IPAddress ip = GetCurrentIp();
if (ip == null) {
return null;
}
try {
CAlternativeNameClass nameClass = new CAlternativeNameClass();
nameClass.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, ip.ToString());
return nameClass;
} catch (Exception e) {
Console.WriteLine(e);
return null;
}
}
The problem is that I'm getting the next error:
System.ArgumentException: Value does not fall within the expected range.
at CERTENROLLLib.CAlternativeNameClass.InitializeFromString(AlternativeNameType Type, String strValue)
What am I doing wrong?
InitializeFromString does not accept an AlternativeNameType of XCN_CERT_ALT_NAME_IP_ADDRESS**. You have to use InitializeFromRawData instead. The error is something of a misnomer because it's not actually the value parameter that's the issue, it's the type, but hey.
InitializeFromRawData takes a string as input (because this is Microsoft, not Ronseal), so you need to encode your raw data as a string so it can turn it in to raw data again:
String ipBase64 = Convert.ToBase64String(ip.GetAddressBytes());
nameClass.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, EncodingType.XCN_CRYPT_STRING_BASE64, ipBase64);
About as intuitive as an Escher artpiece.
** Source: http://msdn.microsoft.com/en-us/library/windows/desktop/aa375024%28v=vs.85%29.aspx
Related
I have a database that stores players stats. The database isn't working with my IP, so I want to get the data from a DNS (like 1.1.1.1)
How can I make C# script to go through the DNS?
The Problem is this Azuara blocks Iranian IP and i want somehow Get a Work Around it
enter image description here
This is my C# code in Unity:
public void GetUserData(OnDataReceivedCallback onDataReceived)
{ //called when the 'Get Data' button on the data part is pressed
if (IsLoggedIn)
{
//ready to send request
StartCoroutine(sendGetDataRequest(LoggedIn_Username, LoggedIn_Password, onDataReceived)); //calls function to send get data request
}
}
IEnumerator sendGetDataRequest(string username, string password, OnDataReceivedCallback onDataReceived)
{
string data = "ERROR";
IEnumerator e = DCF.GetUserData(LoggedIn_Username, LoggedIn_Password); // << Send request to get the player's data string. Provides the username and password
while (e.MoveNext())
{
yield return e.Current;
}
string response = e.Current as string; // << The returned string from the request
if (response == "Error")
{
//There was another error. Automatically logs player out. This error message should never appear, but is here just in case.
LoggedIn_Username = "";
LoggedIn_Password = "";
Debug.Log("Error: Unknown Error. Please try again later.");
}
else
{
data = response;
}
if (onDataReceived != null)
onDataReceived.Invoke(data);
}
The following function successfully returns the FTP server's welcome message when the input IP address is valid.
When I test it with something that has the format of an IP address but doesn't correspond to an FTP server, I get a WebException that is thrown from System.dll, and not from the function. The WebException takes a very long time to get caught, and I would like to avoid relying on try-catch if possible.
How would I fix this so when I pass in an invalid IP address, CheckIP returns "Timeout" (or finishes execution in some other way) instead of dealing with the exception?
Note: I'm aware that connections can be tested with Ping, I just wanted to know if there's a way to do it natively within FTP.
public string CheckIP(string ip){
string respStr="Timeout";
try
{
var connection = (FtpWebRequest)WebRequest.Create(#"ftp://" + ip + #"/");
connection.Credentials = new NetworkCredential(Username, Password);
connection.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
connection.Timeout = 500;
var response = (FtpWebResponse)connection.GetResponse();
respStr = response.WelcomeMessage.ToString();
response.Close();
}
catch (Exception)
{
respStr = "Exception";
}
return respStr;
}
I'm trying to get the user's IP address from ASP.NET MVC 5. I've looked up various examples, such as these:
https://stackoverflow.com/a/740431/177416
https://stackoverflow.com/a/20194511/177416
https://stackoverflow.com/a/3003254/177416
They've all produced the same result: the user is considered internal to the network. I've had friends try their phones (which are not on the network). Here's my latest attempt:
private static Logger _logger = LogManager.GetCurrentClassLogger();
public static bool IsIpInternal()
{
var ipAddress = HttpContext.Current.Request.UserHostAddress;
var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, ipAddress);
_logger.Log(logEvent);
try
{
if (ipAddress != null)
{
var ipParts = ipAddress.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
var isDebug = System.Diagnostics.Debugger.IsAttached;
if (ipParts[0] == 10)
{
return true;
}
}
}
catch (Exception e)
{
logEvent = new LogEventInfo(LogLevel.Error, _logger.Name, e.Message);
_logger.Log(logEvent);
return false;
}
return false;
}
The log is showing 10.xxx.xx.xxx for all requests (based on the log). This is an internal address rather than the IP of the client connecting to the web app. The IsIpInternal() returns true always. What am I doing wrong?
Note that I'm ignoring 192.168.x.x and 172.16.xxx.xxx addresses as being internal.
If your web site is behind a load balancer, it is a common problem for the load balancer's IP address to appear when you are expecting the client's IP address. That is because in reality the load balancer is the only client that the web application knows is talking to it.
There are two ways to deal with this:
You can configure the load balancer to add an additional HTTP header (x-forwarded-for) that specifies the original IP address. You will need to modify your web site to look at this header instead of the UserHostAddress, like this:
//var clientIP = HttpContext.Current.Request.UserHostAddress;
var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"];
Note: The x-forwarded-for header can actually return a comma-delimited list of IP addresses in some cases. So to be compatible with such an occurence, you might write this instead:
var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"].Split(',')[0];
You can configure certain LBs to pass through the client IP by copying the IP header packet. For Citrix Netscaler, see this article for more information.
I am reviewing source code of a voice chat application.
Here I want to run server program, so that any client can contact to server for voice chat. To run my server program I have to pass server name , port number and network interface that I am going to use for voice chat, after passing required arguments I have to call ServerStart method which is done by clicking on Start Checkbox in design view.If user has not passed appropriate type of arguments then it shows error by calling method ShowError().
Now, When I pass serverName, port number and Network Interface then serverName variable reference to null instead of the passed serverName argument.
Why An exception is thrown when I run server program that exception is "The source was not found, but some or all events logs could not be searched. Inaccessible logs: Security."
public partial class ServerWindow
{
private ChatServer server;
public delegate void SetListBoxItem(string str, string type);
public ServerWindow()
{
InitializeComponent();
ObtainNetworkInterfaces();
}
private void cbStartStop_Checked(object sender, RoutedEventArgs e)
{
if (cbStartStop.IsChecked == true)
{
// validate the port number
try
{
var port = Int32.Parse(tbPortNumber.Text);
server = new ChatServer(port, cbInterfaces.SelectedItem, tbServerName.Text);
server.ClientConnected += ServerOnClientConnected;
server.ClientDisconnected += ServerOnClientDisconnected;
var serverName = tbServerName.Text;
if (string.IsNullOrWhiteSpace(serverName))
{
ShowError();
}
else
{
server.StartServer();
SetControls(false);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
if (server == null)
return;
server.StopServer();
SetControls(true);
}
}
private void ShowError()
{
MessageBox.Show(#"Please enter valid port number and/or server name");
cbStartStop.IsChecked = false;
}
The problem seems not to be in the code that you posted. After our chat I would suggest to look at this post try the accepted answer. I have the feeling it will solve your problem.
It is usually helpful to use the exception message in the catch clause. :)
I have written the following code to get the IPv4 address of my machine. When we deploy this code on the server, this code gives me the IP address of the server, but not the machines IP on which application running?
public string getIpAddress()
{
try
{
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
return myIP;
}
catch (Exception)
{
throw;
}
}
This is the expected behavior as this code is running on the server side.
However, if you want to get the client IP address, you can still do it by using the Request object. (See this post for more details or check on google for examples)