Hi i am new to programing and cant see what is wrong with this code
i have a textbox that i will add a host name to and then the S1 string will be add and then pinged all i want the code to do is to list what is the correct host name so if i enter the name Computer in the text box it will ping the following
ComputerDT
ComputerLT
computerTB
computerR0
only one will have the correct host name and i want to list it in list box one its all working fine apart from the last if statement
if (host1 != "")
listBox1.Items.Add(host1);
and i get host1 not in local context i cant see why this is wrong
can anyone help please
public partial class Form1 : Form
{
public string S1 = "DT";
public string S2 = "LT";
public string S3 = "R0";
public string S4 = "TB";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
update();
}
static string Ping(string host)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
string errMessage = string.Empty;
string returnMessage;
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(host, timeout, buffer, options);
if (!(reply == null))
{
switch (reply.Status)
{
case IPStatus.Success:
returnMessage = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
break;
case IPStatus.TimedOut:
returnMessage = "Connection has timed out...";
break;
default:
returnMessage = string.Format("Ping failed: {0}", reply.Status.ToString());
break;
}
}
else
returnMessage = "Connection failed for an unknown reason...";
}
catch (PingException ex)
{
returnMessage = string.Format("");
}
catch (SocketException ex)
{
returnMessage = string.Format("");
}
return returnMessage;
}
public void update()
{
string[] lines = textBox1.Lines;
List<string> myCollection = new List<string>();
string host1;
foreach (string line in lines)
{
if (line.Contains(""))
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
}
myCollection.ToArray();
{
foreach (string val in myCollection)
host1 = Ping(val);
if (host1 != "")
listBox1.Items.Add(host1);
}
}
}
}
avoid using the following constructs
if(condition)
expression;
foreach(condition)
expression;
instead always use braces - you will then spot the problem
You need to wrap your foreach loop in braces:
foreach (string val in myCollection)
{
host1 = Ping(val);
if (host1 != "")
listBox1.Items.Add(host1);
}
otherwise is will only loop the first line. (which is why host1 is no longer in scope)
the if statement above it looks iffy {chuckle} as well:
if (line.Contains(""))
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
should be
if (line.Contains("")) // this will always be true. Need to use a proper check here
{
myCollection.Add(line + S1);
myCollection.Add(line + S2);
myCollection.Add(line + S3);
myCollection.Add(line + S4);
}
Related
I would like to ask, How I can use the While statement for downloading URL?
Here's what I want to happen.
I want to check if the url from CheckBoxListItems is already exist from my ListView
There's a case that I'm adding another urls to my listbox and I don't want to download again.
if url is already exists in my listview it will skip and proceed to the next url(which is not yet downloaded).
Here's my current codes:
int count = 0;
int total = LB.CheckedItems.Count;
string counter = string.Empty;
using (cts = new CancellationTokenSource())
{
try
{
if (cts.IsCancellationRequested) { throw new TaskCanceledException(); }
txtOutput.Text = string.Empty;
Cursor = Cursors.WaitCursor;
Parsing = true;
Text = "Getting links information. Please wait...";
foreach (string url in LB.CheckedItems)
{
var info = await Task.Run(() => Parser.GetJsonData(url, cts.Token));
count++;
counter = "( " + count + " of " + total + " )";
lblTotalLinks.Text = counter;
Text = "Parsing in progress. Please wait... " + counter;
AddToListView(info); //ADD DOWNLOADED STRINGS TO LISTVIEW
}
Text = "Parsing done. " + counter;
}
catch (OperationCanceledException ex)
{ Text = ex.Message; }
catch (Exception ex)
{ MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
Parsing = false;
Cursor = Cursors.Default;
cts = null;
//ADD TO LISTVIEW()
private void AddToListView(MediaInfo info)
{
int count = LV.Items.Count + 1;
var results = new List<ListViewItem> { new ListViewItem(new[]
{
count.ToString(),
info.Series,
"Episode " + info.Episode,
info.Title,
info.Runtime,
info.Resolution,
info.Category,
info.URL, //here's what I want to check if already exists
info.M3u8_url,
info.FileSize,
info.Fragments
})};
ListViewItem[] array = results.ToArray();
LV.BeginUpdate();
LV.ListViewItemSorter = null;
LV.Items.AddRange(array);
LV.Focus();
LV.EndUpdate();
Countlists();
LV.Items[LV.Items.Count - 1].EnsureVisible();
}
this is the example of what I want:
string urlExists = string.Empty;
foreach (ListViewItem item in LV.Items)
{
urlExists = item.SubItems[7].Text;
foreach (string url in LB.CheckedItems)
{
while (url != urlExists)
{
}
}
I have phone numbers stored in the database, I want to retrieve all phone numbers using foreach loop and assign them to variable and send bulk sms, but problem is, I am getting only one number from database. Here is my code:
// GET: Members/SendBatch
public ActionResult SendBatch()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendBatch(Membership member)
{
var db = new ChurchContext();
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
}
}
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
return View("Index", member);
}
public static string GetMinisry(string ministry)
{
string membership = "";
switch (ministry)
{
case "Youth":
membership = "Youth";
break;
case "Children":
membership = "Children";
break;
case "Men":
membership = "Men";
break;
case "Women":
membership = "Women";
break;
case "Visitors":
membership = "Visitors";
break;
case "Members":
membership = "Members";
break;
}
return membership;
}
I would like to get all the phone numbers and assigned them to cell variable and then to sms api and send bulk sms.
Try this (dirty but will do the job):
string mess = member.Message;
string cell = member.Cell;
List<string> cellNumbers = new List<string>(); //LIST OF NUMBERs
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
cellNumbers.add(cell);
}
}
foreach(string number in cellNumbers) // send all the sms
{
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + number;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
You have a cycle where you override cell in each iteration and even though cell received all the values you need, all were overriden by the next one, except for the very last one. When the cycle is finished, you are sending the request using the very last value of cell. This is why you had the illusion that you have got a single value. Actually you have got all the values, but made the mistake of overriding them before using them. The solution is to send the request inside the cycle instead of after the cycle, like this:
// GET: Members/SendBatch
public ActionResult SendBatch()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendBatch(Membership member)
{
var db = new ChurchContext();
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "xxxx";
string user = "xxxx";
string selectministries = member.SelectMinistries;
string pathtoministries = "";
pathtoministries = GetMinisry(selectministries);
if (pathtoministries == "Youth")
{
var youthtable = from e in db.Youths
select e;
var Entyouth = youthtable.ToList();
foreach (Youth y in Entyouth)
{
string youthcell = y.ContactMobile.ToString();
cell = youthcell;
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + mess + "&" +
"msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
return View("Index", member);
}
}
}
public static string GetMinisry(string ministry)
{
string membership = "";
switch (ministry)
{
case "Youth":
membership = "Youth";
break;
case "Children":
membership = "Children";
break;
case "Men":
membership = "Men";
break;
case "Women":
membership = "Women";
break;
case "Visitors":
membership = "Visitors";
break;
case "Members":
membership = "Members";
break;
}
return membership;
}
Thanks guys, your answers solved my problem, hope future visitors to this page with similar problem will get help quickly.
I have c# application where it displays a message on messagebox after the query is run.At the sametime I want it to write a logfile. This is what i tried but no luck. My logfile was empty.
It had created a empty file.
private void backgroundWorker_Import_DoWork(object sender, DoWorkEventArgs e)
{
//Finally, loop through each row in the dataView and execute INSERT Statements against database
int recCount = 0;
successCount = 0;
failedCount = 0;
dv.RowFilter = "execute_bit IN ('1')";
using (MySqlConnection connectionMySql = new MySqlConnection(connectionStringMySql))
{
connectionMySql.Open();
MySqlCommand commandMySql = new MySqlCommand();
commandMySql.Connection = connectionMySql;
foreach (DataRowView rowView in dv)
{
recCount++;
backgroundWorker_Import.ReportProgress(recCount);
commandMySql.CommandText = rowView["sql"].ToString();
try
{
successCount = successCount + commandMySql.ExecuteNonQuery();
//WriteToLogFile("");
//WriteToLogFile("");
**WriteToLogFile(DateTime.Now.ToString() + ", " + recCount.ToString() + "," + successCount.ToString() + "," + failedCount.ToString());
}**
catch (Exception)
{
failedCount++;
}
}
}
}
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string msg = "";
msg = msg + "Records successfully imported: " + successCount.ToString() + Environment.NewLine;
msg = msg + "Records that failed to import: " + failedCount.ToString() + Environment.NewLine + Environment.NewLine;
msg = msg + "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
progressBar1.Visible = false;
MessageBox.Show( msg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
**private void WriteToLogFile(string[] output)
{
StreamWriter sw = null;
FileStream fs = null;
string logfileFileName = System.IO.Path.Combine( "C:/luvi/logfile.txt");
fs = File.Open(logfileFileName, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
foreach (string line in output)
{
sw.WriteLine(line);
}
sw.Close();
sw = null;
}**
You could use File.WriteAllLines as shown in this topic.
Its' syntax is as follows:
public static void WriteAllLines(
string path,
string[] contents
)
In your case you would use it like so:
string logfileFileName = #"C:/luvi/logfile.txt";
File.WriteAllLines(logfileFileName, output);
Note: this overwrites the file, if you want to append them use File.AppendAllLines.
You need to actually call your method aswell, which may be a problem because I do not see that in your code. In the following changes I have replaced the string msg for an array, and added those (you could also use a list and call list.Add).
private void backgroundWorker_Import_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string[] msg = new string[] {};
msg[0] = "Records successfully imported: " + successCount.ToString();
msg[1] = "Records that failed to import: " + failedCount.ToString();
msg[2] = "Records excluded from import (20 minute grace-period): " + (tblVehicles.Rows.Count - successCount - failedCount).ToString();
// Write to log!
WriteToLogFile(msg);
// Show to messagebox.
string showmsg = msg[0] + Environment.NewLine + msg[1] + Environment.NewLine + msg[2];
progressBar1.Visible = false;
MessageBox.Show(showmsg, "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void WriteToLogFile(string[] output)
{
string logfileFileName = "C:/luvi/logfile.txt";
File.AppendAllLines(logfileFileName, output);
}
it seem problem with WriteToLogFile( string[] output) method. You are passing single string while it is expecting arrary of string. catch block is failing it silently.
here is my FULL code below,Please need help, I have been trying to send email via gmail, I get this error "530-5.5.1 Authentication required", the exception occurs in the method called "Send()" on this line here: (see full code below), I am not using the c# library for some reason, so I need to get this to work, thanks.
//EXCEPTION OCCURS HERE, SEE THE SEND METHOD BELOW FOR FULL CODE
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
}
//CONSTRUCTOR
public Smtp()
{
Port =465 ;
Host = "smtp.gmail.com";
Email = "email#gmail.com";
Password = "xxxxxxx";
to = new List<String>() { "reciever#gmail.com"};
from = "sender#gmail.com";
}
//FULLE CODE
public void Connect()
{
if (Client == null)
Client = new TcpClient();
if (!Client.Connected)
Client.Connect(Host, Port);
//if (IsSecure)
//{
SslStream secureStream =
new SslStream(Client.GetStream());
secureStream.AuthenticateAsClient(Host);
ClientStream = secureStream;
secureStream = null;
Console.WriteLine("secure");
//}
//else
//{
// ClientStream = Client.GetStream();
// Console.WriteLine("non secure");
//}
Writer = new StreamWriter(ClientStream);
Reader = new StreamReader(ClientStream);
string c= ReadLine();
Console.WriteLine(c);
string message = "EHLO me";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
// throw new SmtpException(response);
}
Send();
}
// public void
public void Send()
{
string message = "MAIL FROM:<" + Email + ">";
SendCommand(message);
string response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
string x = ReadLine();
Console.WriteLine(x);
**//EXCEPTION OCCURS HERE**
foreach (string address in to)
{
try
{
message = "RCPT TO:<" + address + ">\r\n";
response = ReadLine();
SendCommand(message);
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
}
catch (SmtpException e)
{
System.Console.WriteLine("{ 0}", e.Message);
}
}
message = "DATA\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "354")
{
throw new SmtpException(response);
}
message = "Subject: " + subject + "\r\n";
foreach (string address in to)
{
message += "To: " + address + "\r\n";
}
foreach (string address in cc)
{
message += "Cc: " + address + "\r\n";
}
message += "From: " + from + "\r\n";
if (bodyHtml.Length > 0)
{
message += "MIME-Version: 1.0\r\n"
+ " Content-Type: text/ html;\r\n"
+ " charset=\" iso-8859-1\"\r\n";
message += "\r\n" + bodyHtml;
}
else
{
message += "\r\n" + bodyText;
};
message += "\r\n.\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.Substring(0, 3) != "250")
{
throw new SmtpException(response);
}
message = "QUIT\r\n";
SendCommand(message);
response = ReadLine();
Console.WriteLine(response);
if (response.IndexOf(" 221") == -1)
{
throw new SmtpException(response);
}
}
public void Close()
{
if (Client != null)
{
if (Client.Connected)
Logout();
Client.Close();
Client = null;
}
if (ClientStream != null)
{
ClientStream.Close();
ClientStream = null;
}
if (Writer != null)
{
Writer.Close();
Writer = null;
}
if (Reader != null)
{
Reader.Close();
Reader = null;
}
disposed = true;
}
public void Dispose()
{
if (!disposed)
Close();
}
protected void Login()
{
if (!IsResponseOk(SendCommand("USER " + Email)) ||
!IsResponseOk(SendCommand("PASS " + Password)))
throw new Exception("User/password not accepted");
}
protected void Logout()
{
SendCommand("RSET");
//SendCommand("QUIT");
}
protected string SendCommand(string cmdtext)
{
Writer.WriteLine(cmdtext);
Writer.Flush();
return ReadLine();
}
protected string ReadLine()
{
return Reader.ReadLine() + "\r\n";
}
protected string ReadLines()
{
StringBuilder b = new StringBuilder();
while (true)
{
string temp = ReadLine();
if (temp == ".\r\n" || temp.IndexOf("-ERR") != -1)
break;
b.Append(temp);
}
return b.ToString();
}
protected static bool IsResponseOk(string response)
{
if (response.StartsWith("+OK"))
return true;
if (response.StartsWith("-ERR"))
return false;
throw new Exception("Cannot understand server response: " +
response);
}
Clearly the SMTP server requires authentication before accepting mail to send. This is commonplace as spammers and scammers used to use 'open relays' to peddle their wares.
Check the rules for the server to see what authentication they will accept. The Wikipedia reference at http://en.wikipedia.org/wiki/SMTP_Authentication might be useful.
I am trying write a function that takes a single IP address as a parameter and queries that machine on my local network for it's MAC address.
I have seen many examples that get the local machine's own MAC address, however none (I've found) that seem to query a local network machine for it.
I know such a task is achievable as this Wake on LAN scanner software scans the local IP range and returns MAC address/Hostname of all on machines.
Can anyone tell me where I'd get started trying to write a function to achieve this in C#? Any help would be appreciated. Thanks
EDIT:
As per Marco Mp's comment below, have used ARP tables.
arp class
public string GetMacAddress(string ipAddress)
{
string macAddress = string.Empty;
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a " + ipAddress;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length >= 8)
{
macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
+ "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
+ "-" + substrings[7] + "-"
+ substrings[8].Substring(0, 2);
return macAddress;
}
else
{
return "not found";
}
}
Very late edit:
In open souce project iSpy (https://github.com/ispysoftware/iSpy) they use this code, which is a little nicer
public static void RefreshARP()
{
_arpList = new Dictionary<string, string>();
_arpList.Clear();
try
{
var arpStream = ExecuteCommandLine("arp", "-a");
// Consume first three lines
for (int i = 0; i < 3; i++)
{
arpStream.ReadLine();
}
// Read entries
while (!arpStream.EndOfStream)
{
var line = arpStream.ReadLine();
if (line != null)
{
line = line.Trim();
while (line.Contains(" "))
{
line = line.Replace(" ", " ");
}
var parts = line.Trim().Split(' ');
if (parts.Length == 3)
{
string ip = parts[0];
string mac = parts[1];
if (!_arpList.ContainsKey(ip))
_arpList.Add(ip, mac);
}
}
}
}
catch (Exception ex)
{
Logger.LogExceptionToFile(ex, "ARP Table");
}
if (_arpList.Count > 0)
{
foreach (var nd in List)
{
string mac;
ARPList.TryGetValue(nd.IPAddress.ToString(), out mac);
nd.MAC = mac;
}
}
}
https://github.com/ispysoftware/iSpy/blob/master/Server/NetworkDeviceList.cs
Update 2 even more late, but I think is best because it uses regex that checks better for exact matches.
public string getMacByIp(string ip)
{
var macIpPairs = GetAllMacAddressesAndIppairs();
int index = macIpPairs.FindIndex(x => x.IpAddress == ip);
if (index >= 0)
{
return macIpPairs[index].MacAddress.ToUpper();
}
else
{
return null;
}
}
public List<MacIpPair> GetAllMacAddressesAndIppairs()
{
List<MacIpPair> mip = new List<MacIpPair>();
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a ";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string cmdOutput = pProcess.StandardOutput.ReadToEnd();
string pattern = #"(?<ip>([0-9]{1,3}\.?){4})\s*(?<mac>([a-f0-9]{2}-?){6})";
foreach (Match m in Regex.Matches(cmdOutput, pattern, RegexOptions.IgnoreCase))
{
mip.Add(new MacIpPair()
{
MacAddress = m.Groups["mac"].Value,
IpAddress = m.Groups["ip"].Value
});
}
return mip;
}
public struct MacIpPair
{
public string MacAddress;
public string IpAddress;
}
using System.Net;
using System.Runtime.InteropServices;
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);
try
{
IPAddress hostIPAddress = IPAddress.Parse("XXX.XXX.XXX.XX");
byte[] ab = new byte[6];
int len = ab.Length,
r = SendARP((int)hostIPAddress.Address, 0, ab, ref len);
Console.WriteLine(BitConverter.ToString(ab, 0, 6));
}
catch (Exception ex) { }
or with PC Name
try
{
Tempaddr = System.Net.Dns.GetHostEntry("DESKTOP-xxxxxx");
}
catch (Exception ex) { }
byte[] ab = new byte[6];
int len = ab.Length, r = SendARP((int)Tempaddr.AddressList[1].Address, 0, ab, ref len);
Console.WriteLine(BitConverter.ToString(ab, 0, 6));
Just a better performing version of the accepted method.
public string GetMacByIp( string ip )
{
var pairs = this.GetMacIpPairs();
foreach( var pair in pairs )
{
if( pair.IpAddress == ip )
return pair.MacAddress;
}
throw new Exception( $"Can't retrieve mac address from ip: {ip}" );
}
public IEnumerable<MacIpPair> GetMacIpPairs()
{
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a ";
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string cmdOutput = pProcess.StandardOutput.ReadToEnd();
string pattern = #"(?<ip>([0-9]{1,3}\.?){4})\s*(?<mac>([a-f0-9]{2}-?){6})";
foreach( Match m in Regex.Matches( cmdOutput, pattern, RegexOptions.IgnoreCase ) )
{
yield return new MacIpPair()
{
MacAddress = m.Groups[ "mac" ].Value,
IpAddress = m.Groups[ "ip" ].Value
};
}
}
public struct MacIpPair
{
public string MacAddress;
public string IpAddress;
}
With SharpPCap, It will work on Windows & Linux
public string getMacAdress(string ip){
LibPcapLiveDeviceList devices = LibPcapLiveDeviceList.Instance;//list all your network cards
ARP arp = new ARP(devices[0]);//select the first network card by default
IPAddress ip = IPAddress.Parse(ip);
PhysicalAddress macAdress = arp.Resolve(ip);
return macAdress.ToString();
}
As per Marco Mp's comment above, have used ARP tables. arp class