I am really unfamiliar with C#, it's been years since I've programmed with this language. I'm going to post the code I have, which has build errors. This is what I'm trying to do, but I really am not sure how to proceed. I have hit a wall and really have no clue how to proceed:
Enter an address (as a string)
Resolve the address using the appropriate function
Print out the complete host information
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace CSDNS
{
class Program
{
static void PrintHostInfo(String host)
{
{
IPHostEntry hostinfo;
try
{
hostinfo = Dns.GetHostEntry("www.sunybroome.edu"); // DNS Name Resolution
//
// The IP address is now in hostinfo structure
// Print out the contents of hostinfo structure
// in an easily readable form with labels. For
// example, the host name can be output using:
Console.WriteLine("Hostname = {0}\n", hostinfo.HostName);
}
catch
{
// Print out the exception here...
}
try
{
IPHostEntry hostInfo;
//Attempt to resolve DNS for given host or address
hostInfo = Dns.Resolve(host);
//Display the primary host name
Console.WriteLine("\tCanonical Name: " + hostInfo.HostName);
//Display list of IP addresses for this host
Console.Write("\tIP Addresses: ");
foreach (IPAddress ipaddr in hostInfo.AddressList)
{
Console.Write(ipaddr.ToString() + " ");
}
Console.WriteLine();
//Display list of alias names for this host
Console.Write("\tAliases: ");
foreach (String alias in hostInfo.Aliases)
{
Console.Write(alias + " ");
}
Console.WriteLine("\n");
}
catch (Exception)
{
Console.WriteLine("\tUnable to resolve host: " + host + "\n");
}
}
}
static void Main(string[] args)
{
//Get and print local host info
try
{
Console.WriteLine("Local Host:");
String localHostName = Dns.GetHostName();
Console.WriteLine("\tHost Name: " + localHostName);
PrintHostInfo(localHostName);
}
catch (Exception)
{
Console.WriteLine("Unable to resolve local host\n");
}
//Get and print info for hosts given on command line
foreach (String arg in args)
{
Console.WriteLine(arg + ":");
PrintHostInfo(arg);
}
}
}
}
You need to pass in host to the Resolve method, not hostInfo (i.e. the string that contains the host you want to resolve):
hostInfo = Dns.Resolve(host);
Related
This is the code I have:
/*
* This is a C# Program which displays the URL of an input IP address.
*/
using System;
using System.Net;
namespace CNT4704L
{
class MySocketLab
{
static void Main()
{
Console.Write("Enter an IP address (e.g., 131.247.2.211): ");
IPAddress addr = Console.ReadLine();
string strSiteName = Dns.GetHostEntry(addr);
Console.Write("\nHost name of ", addr);
Console.Write(" is ", strSiteName);
}
}
}
It says I can't implicitly convert type string to System.Net.IPAddress, but I'm not sure what the Url I'm trying to get could be other than a string.
Your problem is on this line:
IPAddress addr = Console.ReadLine();
The Console.ReadLine function returns a string not a IPAddress.
Just change it to:
var addr = Console.ReadLine();
I need to generate UUID for my Machine Mac address. Also i want extract the mac address from UUID.
I know we can use below two methods for encoding and decoding. But it will generate the encrypted string only not UUID.
Encode:
System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(plainTextBytes));
Decode:
System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(base64EncodedData));
But for my requirement i want to generate(encode) the UUID and extract(decode) the mac address . How to do this in C# code?
You can get the MAC address using the following code.
From our tests it will return null on about 1.3% of machines (probably some form of virtual machine or something very locked down).
MAC Address of first IP enabled device
public static string GetMACAddress()
{
try
{
using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (ManagementObjectCollection moc = mc.GetInstances())
{
if (moc != null)
{
foreach (ManagementObject mo in moc)
{
try
{
Trace.WriteLine(mo["Index"] + " Mac " + mo["Caption"] + " : " + mo["MacAddress"] + " Enabled " + (bool)mo["IPEnabled"]);
if (mo["MacAddress"] != null && mo["IPEnabled"] != null && (bool)mo["IPEnabled"] == true)
{
return mo["MacAddress"].ToString();
}
}
finally
{
mo.Dispose();
}
}
}
}
}
}
catch (Exception ex)
{
Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
}
return null;
}
I'm writing a part of a program that shall copy a batch of files from the current computer to a defined list of computers.
If these computers are not available, the code will hang for a long time trying to access them. Is there any functionallity in C# to check if the machine is available and then skip if it's not?
MFWs = File.ReadAllLines(GuiManager.MyConfigManagerConfig.MachinesList);
foreach (string MFW in MFWs)
{
if (MFW != System.Environment.MachineName)
{
String target = #"\\" + MFW + #"\D\IbSi\config\" + Path.GetFileName(ConfigFile);
String backup = #"\\" + MFW + #"\D\IbSi\userdata\" + Path.GetFileName(ConfigFile);
try
{
File.Copy(source, target, true);
File.Copy(source, backup, true);
}
catch (Exception ex)
{
Manager.SendMessage("Failed to copy " + Path.GetFileName(ConfigFile) + " to " + MFW + "\n" + ex.Message);
}
}
}
You could ping the computer before starting the copy (taken from this answer):
using System.Net.NetworkInformation;
public static bool IsHostAvailable(string nameOrAddress)
{
bool pingable = false;
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
return pingable;
}
As noted in the comments you need to make sure the firewall on the servers is open for pings (ICMP echo requests)
I'm new to C# and have a question.
My server has log files with lines like
2015-05-14 20:56:50 72.167.255.87 GET
/images/email/site_05_12_2015/email-contactus-button.png
- 80 - 50.48.46.50 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.2;+WOW64;+Trident/7.0;+Microsoft+Outlook+15.0.4711;+Microsoft+Outlook+15.0.4711;+ms-office;+MSOffice+15)
304 0 0 46
and my program is intended to collect the unique IP addresses that request a certain asset. In the above line I would extract "50.48.46.50" if the program was searching for "email-contactus-button.png".
Here it is:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
// args[0] = expression to search for, e.g. "cloudrealized-email-top-banner"
try
{
string [] logs = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory());
Console.WriteLine("{0} log files found", logs.Length);
HashSet<string> ipList;
string ipreg = "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$";
foreach (string thislog in logs)
{
using (StreamReader sr = new StreamReader(thislog))
{
Console.WriteLine("Checking log file {0} for expression '{1}' ...\n", thislog, args[0]);
String line = sr.ReadToEnd();
if (line.Contains(args[0]))
{
Match thisip = Regex.Match(line,ipreg);
thisip = thisip.NextMatch();
if (thisip.ToString() != args[1]) ipList.Add(thisip);
}
//for (Match m = Regex.Match(line,regx); m.Success; m = m.NextMatch()) ++count;
}
}
Console.WriteLine("\n\nRESULT:\n\nThe asset {0} was requested {1} times.", args[0], ipList.Count());
Console.WriteLine("Unique IPs:");
foreach (string s in ipList) Console.WriteLine(s);
}
catch (Exception e)
{
Console.WriteLine("Error occured: ");
Console.WriteLine(e.Message);
}
}
}
The first compiler warning I'm getting is on the line
string ipreg = "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$";
because it thinks I'm trying to escape the . character. How can I fix that?
The other two warnings are on the methods I call on iplist. They are not recognized, and I can't figure out why. The documentation I was looking at for HashSet is https://msdn.microsoft.com/en-us/library/bb359438%28v=vs.110%29.aspx.
Here is a basic C# example of a regex expression to pull out that IP address. This is assuming that all of your log files will be structured the same way.
string strRegex = #"(?<=-\s)([0-9]{1,3}\.){3}[0-9]{1,3}";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"2015-05-14 20:56:50 72.167.255.87 GET /images/email/site_05_12_2015/email-contactus-button.png - 80 - 50.48.46.50 Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.2;+WOW64;+Trident/7.0;+Microsoft+Outlook+15.0.4711;+Microsoft+Outlook+15.0.4711;+ms-office;+MSOffice+15) 304 0 0 46";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
The following code returns only three serial ports (com3, com4 and com5). The firmware that I would like to access is located on a USB plug multiplier. How can I access the serial ports of this mulitplier and how can I identify the specific USB containing the firmware that I want to send information to?
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class SerialPortExample
{
public static void Main()
{
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
foreach (string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
}
}
}
Many thanks in advance!
This is a pretty big usability problem and caused by USB drivers taking a shortcut and emulating a serial port to make it easy to interface with them. Serial ports are very primitive devices, which makes their api very easy to use. But lacks any kind of support for plug-and-play, there's no way to get a decent notification for them. The driver just picks an arbitrary port number and it is up to the user to figure out which one it might be. Trial and error stuff. This didn't use to be a problem, serial ports had a connector mounted on the machine's back panel that was clearly labeled with the COM port name.
You can possibly get some mileage out of WMI, it lets you enumerate serial port devices with the Win32_SerialPort query. What you get is fairly unpredictable, it completely depends on the driver to supply the data. Best way to experiment with that is with the WMI Code Creator utility, it can also auto-generate the C# code you need. Unfortunately I can't find the download location anymore, this appears to have been removed in the past couple of weeks. Hope you can find an alternative.
The code below does a good job finding the specific ports:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Windows.Forms;
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
MyClass x = new MyClass();
var com = x.GetCOMs();
foreach (string port in com)
{
Console.WriteLine(port);
}
Console.ReadLine();
}
}
class MyClass
{
public List<string> GetCOMs()
{
List<string> coms = new List<string>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
foreach (ManagementObject obj in searcher.Get())
{
object captionObj = obj["Caption"];
if (captionObj != null)
{
string caption = captionObj.ToString();
if (caption.Contains("(COM"))
{
coms.Add(caption);
}
}
}
m_ParseCOMs(ref coms);
}
catch (ManagementException ex)
{
MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
return coms;
}
return coms;
}
private void m_ParseCOMs(ref List<string> comPorts)
{
string[] temp;
List<string> temp2 = new List<string>();
int index = 0;
foreach (string s in comPorts)
{
string temp3 = "";
temp = s.Split(' ');
temp3 += temp[temp.Length - 1] + " - ";
for (int i = 0; i < temp.Length - 1; i++)
{
temp3 += temp[i] + " ";
}
temp2.Insert(index, temp3);
index++;
}
comPorts = temp2;
}
}
}