set blank ip address or remove ip adddress - c#

I want to set ip address, subnet, gateway & dns; there is no issue in setting up but once the ip address is applied i'm trying to delete the existing gateway, pref dns its not working.
I tried to send a empty string but its always picking up .... (4dots) instead of empty string.
How can i set empty ip address or delete the gateway & pref dns ipaddress using the below method?
Get ip address from textbox usercontrol:
string[] pdns = ipsefpredns.GetIPaddress();
string str_pdns = pdns[0].ToString() + "." + pdns[1].ToString() + "." + pdns[2].ToString() + "." + pdns[3].ToString();
string ipaddressprefdns;
string emptypdns = pdns[0].ToString() + pdns[1].ToString() + pdns[2].ToString() + pdns[3].ToString();
if (pdns == null || pdns.Length ==0) //if the array is empty,null get empty string
{
ipaddressprefdns = emptypdns;
}
else
{
ipaddressprefdns = str_pdns;
}
Method to apply ipaddress:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "netsh");
Process.Start(new ProcessStartInfo(fileName)
{
Arguments = string.Format("interface ip set address \"{0}\" static {1} {2} {3}", nicname, ipaddressstatic, ipaddresssubnet, ipaddressgateway),
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();
Process.Start(new ProcessStartInfo(fileName)
{
Arguments = string.Format("interface ip set dns \"{0}\" static {1} Primary", nicname, ipaddressprefdns),
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();

I found a solution by reading the array then compare withit, pass none to gateway address.
string[] pdns = ipsefpredns.GetIPaddress();
string str_pdns = pdns[0].ToString() + "." + pdns[1].ToString() + "." + pdns[2].ToString() + "." + pdns[3].ToString();
string ipaddressprefdns="";
string prefdnss = UsingLoopStringBuilder(pdns);
if (!String.IsNullOrEmpty(prefdnss))
{
ipaddressprefdns = str_pdns;
}
else
{
ipaddressprefdns = "none";
}
//method to read string array[]
public string UsingLoopStringBuilder(string[] array)
{
var result = new StringBuilder();
foreach (var item in array)
{
result.Append(item);
}
return result.ToString();
}

Related

find numbers and save to string

I am trying to make a ui that gets the session id of a computer on the network. I want to take this session id and save it to a string to be used later.
private void button1_Click(object sender, EventArgs e)
{
string ComputerName = ComputerNameBox.Text;
string Username = UserNameBox.Text;
Process Process = new Process();
Process.StartInfo.FileName = "CMD.exe";
Process.StartInfo.Arguments = "/K" + "qwinsta /server:" + ComputerName + " " + Username;
Process.StartInfo.CreateNoWindow = true;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.RedirectStandardOutput = true;
Process.Start();
Process.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
Process.BeginOutputReadLine();
while (!Process.HasExited)
{
Application.DoEvents();
}
}
private void SortOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (MessagePop.InvokeRequired)
{
MessagePop.BeginInvoke(new DataReceivedEventHandler(SortOutputHandler), new[] { sendingProcess, outLine });
}
else
{
MessagePop.AppendText(Environment.NewLine + outLine.Data);
}
}
This code runs and inputs the computername and username of the computer/person you want the session ID for. The username and ID will likely be different every time so I can't hard code it.
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console mlynch 9 Active
This is the output I get in the textbox, I want to get the 9 and save it to a string, however, the number can be something like 10 or higher so I will need to be able to get both numbers. How do I do this?
Please try this:
var textBoxData =
"SESSIONNAME USERNAME ID STATE TYPE DEVICE\r\nconsole mlynch 9 Active";
var stringCollection = textBoxData.Split(new[] { Environment.NewLine, " " }, StringSplitOptions.RemoveEmptyEntries);
var finalCollection = new List<int>();
foreach (var s1 in stringCollection)
{
int n;
if (int.TryParse(s1, out n))
{
finalCollection.Add(n);
}
}
(or) create a function which takes in text box data and return int colleciton:
public List<int> GetData(string textBoxData)
{
var stringCollection = textBoxData.Split(new[] { Environment.NewLine, " " }, StringSplitOptions.RemoveEmptyEntries);
var finalCollection = new List<int>();
foreach (var s1 in stringCollection)
{
int n;
if (int.TryParse(s1, out n))
{
finalCollection.Add(n);
}
}
}
and then use it as
var intCollection = GetData(textBox1.Text);
I get in trouble for linking to my open source project UltimateHelper, but just pretend Word is a string.
public static List<Word> GetWords(string sourceText, char[] delimiters = null)
{
// initial value
List<Word> words = new List<Word>();
// typical delimiter characters
char[] delimiterChars = { ' ', '-', '/', ',', '.', ':', '\t' };
// if the delimiters exists
if (delimiters != null)
{
// use the delimiters passedin
delimiterChars = delimiters;
}
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] strings = sourceText.Split(delimiterChars);
// now iterate the strings
foreach (string stringWord in strings)
{
// verify the word is not an empty string or a space
if (!String.IsNullOrEmpty(stringWord))
{
// Create a new Word
Word word = new Word(stringWord);
// now add this word to words collection
words.Add(word);
}
}
}
// return value
return words;
}
I have this in a class called WordParser, so to call it:
Edit: If you need to parse each line, there is also a method:
List<TextLine> textLines = WordParser.GetTextLines(text);
In your case, you want to parse on just space, so set Delimiters to this:
char[] delimiterChars = { ' ' };
List<Word> words = WordParser.GetWords(text, delimiterChars);
// Here is the full example using DataJuggler.Core.UltimateHelper Nuget package
if ((ListHelper.HasOneOrMoreItems(words)) && (words.Count >= 3))
{
Word idWord = Words[2];
int idValue = NumericHelper.ParseInteger(idWord.Text, 0, -1);
}
idValue will be the Id if it parses, 0 if it can't be parsed, and -1 if an error occurs trying to parse it.
I hope I didn't offend anyone by not posting all the classes used, but if it does I will post the full class for each, but kind of overkill to demonstrate a 3 line of code solution.
Hope it helps.
The full code is here:
https://github.com/DataJuggler/UltimateHelper/tree/master/UltimateHelper
And Word Parser:
https://github.com/DataJuggler/UltimateHelper/blob/master/UltimateHelper/WordParser.cs
Word class:
https://github.com/DataJuggler/UltimateHelper/blob/master/UltimateHelper/Objects/Word.cs
List Helper:
https://github.com/DataJuggler/UltimateHelper/blob/master/UltimateHelper/ListHelper.cs
And Numeric Helper:
https://github.com/DataJuggler/UltimateHelper/blob/master/UltimateHelper/NumericHelper.cs
I figured out how to do what I needed.
Process GetSessionID = new Process();
GetSessionID.StartInfo.FileName = "CMD.exe";
GetSessionID.StartInfo.Arguments = "/C" + "for /f \"skip=1 tokens=3\" %1 in ('query user " + Username + "/server:" + ComputerName + "') do #echo %1";
GetSessionID.StartInfo.RedirectStandardOutput = true;
GetSessionID.StartInfo.UseShellExecute = false;
GetSessionID.StartInfo.CreateNoWindow = true;
GetSessionID.Start();
SessionIDOutput = GetSessionID.StandardOutput.ReadToEnd();
GetSessionID.WaitForExit();
DoAllTheThingsTextBox.Text = SessionIDOutput;
if (GetSessionID.HasExited == true)
{
var digitArray = DoAllTheThingsTextBox.Text.Where(Char.IsDigit).ToArray();
SessionID = new String(digitArray);
if (MouseControlCheck.Checked == true)
{
Process Process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe", "/C" + "mstsc /shadow:" + SessionID + " /v " + ComputerName + " /control");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
Process = Process.Start(startInfo);
}
else
{
Process Process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe", "/C" + "mstsc /shadow:" + SessionID + " /v " + ComputerName);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
Process = Process.Start(startInfo);
}
}

How to get Client or visitor IP Address:: Despite multiple tries Didn't get solution:

How to get Client or visitor IP Address:: Despite multiple tries Didn't get solution: Below what I tried:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ipAddress33 = Request.UserHostAddress.ToString();
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress22 = System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString();
Response.Write("System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString(); : " + clientIPAddress22 + "<br />");
string ipaddress;
string IP = Request.UserHostAddress;
string clientIPAddress = this.Page.Request.ServerVariables["REMOTE_ADDR"];
string IP2 = Environment.GetEnvironmentVariable("CLIENTNAME");
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
ipaddress = Request.ServerVariables["REMOTE_ADDR"];
Response.Write("Request.ServerVariables['HTTP_X_FORWARDED_FOR'] : " + ipaddress + "<br />");
Response.Write("Request.UserHostAddress.ToString() : " + ipAddress33 + "<br />");
string stringIpAddress;
stringIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
{
stringIpAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
}
Response.Write("Request.ServerVariables['REMOTE_ADDR'] : " + stringIpAddress + "<br />");
//Get the Host Name
string stringHostName = Dns.GetHostName();
//Get The Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get The Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
Response.Write("Dns.GetHostName(): " + arrIpAddress[arrIpAddress.Length - 1].ToString());
}
}
This is the results I got:
System.Net.Dns.GetHostAddresses(strHostName).GetValue(1).ToString(); : 190.80.90.75
Request.ServerVariables['HTTP_X_FORWARDED_FOR'] : 190.80.90.225
Request.UserHostAddress.ToString() : 190.80.90.225
Request.ServerVariables['REMOTE_ADDR'] : 190.80.90.225
Dns.GetHostName(): 190.80.90.75
Which is not the correct IP address of the visitor.
according to this answer you can use this :
protected void GetUser_IP()
{
string VisitorsIPAddr = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
}
uip.Text = "Your IP is: " + VisitorsIPAddr;
}
VB.Net Version::
-----------------------------------------------
Shared Sub GetUser_IP()
If HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR") IsNot Nothing Then
VisitorsIPAddr = HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR").ToString()
ElseIf HttpContext.Current.Request.UserHostAddress.Length <> 0 Then
VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress
End If
End Sub

Appended strings in message body not being sent in email using SMTPClient() and StringBuilder()

First and foremost I am very new to C# and am sure most of my code could be cleaned up so please don't suggest it unless you are also offering help with my issue.
I am sending an email via SmtpClient(). I am trying to build the body of the email using strings which are returned from functions in loops. My issue is that the string for the body isn't building how I thought it should.
Currently, I am creating a new StringBuilder() with some default text in it. I am then running some functions and trying to add the results to the StringBuilder() object via StringBuilder.AppendLine().
Here is (some of) my code:
// Setup SMTP Client for sending mail updates
//-----------------------------------
String from_addr_text = "<removed>";
String to_addr_text = "<removed>";
String msg_subject = "Updates to USPTO searches";
StringBuilder msg_body = new StringBuilder("The following searches have received updated results:" + Environment.NewLine);
SmtpClient AlertMail = new SmtpClient
{
Port = 587,
Host = "<removed>",
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("<removed>", "<removed>")
};
MailMessage update = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body.ToString())
{
BodyEncoding = UTF8Encoding.UTF8,
IsBodyHtml = false,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
...
// Process data from api for Assignor
//-----------------------------------
bool isUpdated = false;
foreach (String url in searchesByAssignorUSPTO)
{
try
{
String longName = <removed>);
String name = <removed>;
String thisHash = await GetSearchData(url, name, "Assignor");
if (DoesHashExist(thisHash))
{
Debug.WriteLine(thisHash + " already exists. No update to " + name + " search.");
}
else
{
Debug.WriteLine(thisHash + " does not exist. There is an update to " + name + " search.");
isUpdated = true;
msg_body.AppendLine(name + " as " + "Assignor" + Environment.NewLine);
}
}
catch
{
Console.WriteLine("something is broken with ASSIGNOR search dummy!");
}
}
// Process data from api for Assignee
foreach (String url in searchesByAssigneeUSPTO)
{
try
{
String longName = <removed>;
String name = <removed>;
String thisHash = await GetSearchData(url, name, "Assignee");
if (DoesHashExist(thisHash))
{
Debug.WriteLine(thisHash + " already exists. No update to " + name + " search.");
}
else
{
Debug.WriteLine(thisHash + " does not exist. There is an update to " + name + " search.");
isUpdated = true;
msg_body.AppendLine(name + " as " + "Assignee" + Environment.NewLine);
}
}
catch
{
Console.WriteLine("something is broken with ASSIGNEE search dummy!");
}
}
// Send email is search results are updated
if (isUpdated)
{
AlertMail.Send(update);
Debug.WriteLine(msg_body.ToString());
}
When the program runs and there are results returned from the loops, msg_body is printed to the output window correctly but, when the email is received the body is only: "The following searches have received updated results:".
I have tried:
changing the value of isBodyHtml to true and used <br />
instead of Environment.NewLine.
adding \n to end of stringing and removing Environment.NewLine.
changing msg_body to type String and concatenating results to msg_body using =+.
using the Append() method instead of AppendLine().
Here is a snip of the output window:
Be sure to watch the assignment of variables in your code. When you assign msg_body to the update MailMessage object, it's only inputting the one line mentioned that is being returned in the email and doesn't include the information generated by the API.
Try moving the intialization of your SmtpClient and MailMessage variables to right before the if (isUpdated) block and you should be good to go.
per #tym32167, I needed to move the instantiation of MailMessage() to AFTER my loops and functions were completed. I was creating the object before the AppendLines() methods were called and therefore they weren't being included.

IP address of the user who is browsing my website

I want to know the IP address of the client machine, i.e. the IP address of the user who is browsing my website. I am trying the following code but it is returning server address -
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;
}
How can I find the right IP address?
Client IP can be read from request:
context.Request.ServerVariables["REMOTE_HOST"]
Here is code for getting more than just client IP address:
string browserInfo =
"RemoteUser=" + context.Request.ServerVariables["REMOTE_USER"] + ";\n"
+ "RemoteHost=" + context.Request.ServerVariables["REMOTE_HOST"] + ";\n"
+ "Type=" + context.Request.Browser.Type + ";\n"
+ "Name=" + context.Request.Browser.Browser + ";\n"
+ "Version=" + context.Request.Browser.Version + ";\n"
+ "MajorVersion=" + context.Request.Browser.MajorVersion + ";\n"
+ "MinorVersion=" + context.Request.Browser.MinorVersion + ";\n"
+ "Platform=" + context.Request.Browser.Platform + ";\n"
+ "SupportsCookies=" + context.Request.Browser.Cookies + ";\n"
+ "SupportsJavaScript=" + context.Request.Browser.EcmaScriptVersion.ToString() + ";\n"
+ "SupportsActiveXControls=" + context.Request.Browser.ActiveXControls + ";\n"
+ "SupportsJavaScriptVersion=" + context.Request.Browser["JavaScriptVersion"] + "\n";
string IPAddress = string.Empty;
string SearchName = string.Empty;
String strHostName = HttpContext.Current.Request.UserHostAddress.ToString();
IPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.
Refer method GetVisitorIPAddress from developersnote.com blog .
/// <summary>
/// method to get Client ip address
/// </summary>
/// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
/// <returns></returns>
public static string GetVisitorIPAddress(bool GetLan = false)
{
string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(visitorIPAddress))
visitorIPAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
{
GetLan = true;
visitorIPAddress = string.Empty;
}
if (GetLan)
{
if (string.IsNullOrEmpty(visitorIPAddress))
{
//This is for Local(LAN) Connected ID Address
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Get Ip Address From The Ip Host Entry Address List
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
try
{
visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
catch
{
try
{
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
try
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
visitorIPAddress = arrIpAddress[0].ToString();
}
catch
{
visitorIPAddress = "127.0.0.1";
}
}
}
}
}
return visitorIPAddress;
}
string myIP = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();
Note: For getting the public ip address this is used.

Get a machines MAC address on the local network from its IP in C#

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

Categories

Resources