There are two programs that I made that didn't work. There are the server and the client. The server accepts many client by giving a user an ID (starting from 0). The server sends out the command to the specific client based up the server's id. (Example: 200 client are connected to 1 server. The server's selected id is '5', so the server will send the command to all of the client, and the client will ask the server what ID he wants to execute his command on, and if it's '5', that client will execute and send data to the server). The client has many commands, but to create the smallest code with the same error, I only use 1 command (dir). Basically, the server sends the command to the client and if it matches with the client current id and the server current id, it will process the command. By default, the server's current ID is 10. Here are the list of the commands to help the people who wants to answer:
Server Command:
list (Shows all of the users ID connected and the server's current ID) --> Happens on server
dir (request the client to send its dir listing) --> Sent by the client, read by the Server
set (set the server's current id to any number) (example: 'set 4')
Client:
using System;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace clientControl
{
class Program
{
public static string directory = #"C:\";
public static int id = -10;
public static Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
Connect();
getSession();
ReadResponse(sck);
}
static byte[] readResponseFunc()
{
long fileSize = 0;
string fileSizeInString = null;
byte[] fileSizeInByteArray = new byte[1024];
int fileSizeLength = sck.Receive(fileSizeInByteArray);
for (int i = 0; i < fileSizeLength; i++)
{
fileSizeInString = fileSizeInString + (char)fileSizeInByteArray[i];
}
try
{
fileSize = Convert.ToInt64(fileSizeInString);
}
catch { Console.WriteLine(fileSizeInString); }
sck.Send(Encoding.ASCII.GetBytes("a"));
byte[] responseUnknown = new byte[1];
sck.Receive(responseUnknown);
if (Encoding.ASCII.GetString(responseUnknown) == "b")
{
byte[] dataInByteArray = new byte[fileSize];
int dataLength = sck.Receive(dataInByteArray);
return dataInByteArray;
}
return Encoding.ASCII.GetBytes("ERROR RESPONSE FUNC");
}
static void getSession()
{
byte[] message_1 = Encoding.ASCII.GetBytes("make_id");
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
byte[] receivedID = readResponseFunc();
id = Convert.ToInt32(Encoding.ASCII.GetString(receivedID));
}
static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
static void ReadResponse(Socket sck)
{
while (true)
{
if (SocketConnected(sck) == true)
{
try
{
string response = Encoding.ASCII.GetString(readResponseFunc());
byte[] message_1 = Encoding.ASCII.GetBytes("get_id");
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
byte[] response_2InByteArray = readResponseFunc();
string response_2 = Encoding.ASCII.GetString(response_2InByteArray);
if (Convert.ToInt32(response_2) == id)
{
if (response == "dir")
{
string resultOfDirring = "Current Directory: " + directory + "\n\n";
string[] folderListingArray = Directory.GetDirectories(directory);
foreach (string dir in folderListingArray)
{
string formed = "DIRECTORY: " + Path.GetFileName(dir);
resultOfDirring = resultOfDirring + formed + Environment.NewLine;
}
string[] fileListingArray = Directory.GetFiles(directory);
foreach (var file in fileListingArray)
{
FileInfo fileInfo = new FileInfo(file);
string formed = "FILE: " + Path.GetFileName(file) + " - FILE SIZE: " + fileInfo.Length + " BYTES";
resultOfDirring = resultOfDirring + formed + Environment.NewLine;
}
byte[] message_11 = Encoding.ASCII.GetBytes(resultOfDirring);
sck.Send(Encoding.ASCII.GetBytes(message_11.Length.ToString()));
byte[] responseUnknown_11 = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown_11) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_11);
}
}
}
else { }
}
catch { if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }; }
}
else if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
static void Connect()
{
while (true)
{
try
{
sck.Connect(IPAddress.Parse("127.0.0.1"), 80);
break;
}
catch { }
}
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Threading;
namespace serverControl
{
class Program
{
public static int ftpNum = 1;
public static List<int> listOfClient = new List<int>();
public static TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
public static string message = null;
public static int id = 0;
public static int selected_id = 10;
static void Main(string[] args)
{
server.Start();
Thread startHandlingClientThread = new Thread(startHandlingClient);
startHandlingClientThread.Start();
while (true)
{
Console.Write(":> ");
string rawmessage = Console.ReadLine();
if (rawmessage == "list")
{
Console.WriteLine("SELECTED ID: " + selected_id);
Console.WriteLine("List of Clients ID:");
for (int i = 0; i < listOfClient.Count; i++)
{
Console.WriteLine(listOfClient[i]);
}
message = rawmessage+"PREVENT_REPETITION_IN_COMMAND";
}
else if (rawmessage.Contains("set ")) { int wantedChangeId = Convert.ToInt32(rawmessage.Replace("set ", "")); selected_id = wantedChangeId; message = rawmessage+ "PREVENT_REPETITION_IN_COMMAND"; }
else
{
message = rawmessage;
}
}
}
static byte[] readResponseFunc(Socket sck)
{
long fileSize = 0;
string fileSizeInString = null;
byte[] fileSizeInByteArray = new byte[1024];
int fileSizeLength = sck.Receive(fileSizeInByteArray);
for (int i = 0; i < fileSizeLength; i++)
{
fileSizeInString = fileSizeInString + (char)fileSizeInByteArray[i];
}
fileSize = Convert.ToInt64(fileSizeInString);
sck.Send(Encoding.ASCII.GetBytes("a"));
byte[] responseUnknown = new byte[1];
sck.Receive(responseUnknown);
if (Encoding.ASCII.GetString(responseUnknown) == "b")
{
byte[] dataInByteArray = new byte[fileSize];
int dataLength = sck.Receive(dataInByteArray);
return dataInByteArray;
}
return Encoding.ASCII.GetBytes("ERROR RESPONSE FUNC");
}
static void startHandlingClient()
{
while (true)
{
handleClient(server);
}
}
static void handleClient(TcpListener clientToAccept)
{
Socket sck = clientToAccept.AcceptSocket();
Thread myNewThread = new Thread(() => ReadResponse(sck));
myNewThread.Start();
}
static bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
static void ReadResponse(Socket sck)
{
Thread myNewThread = new Thread(() => SendtoClient(sck));
myNewThread.Start();
Thread.Sleep(2000);
while (true)
{
if (SocketConnected(sck) == true)
{
try
{
byte[] dataInByteArray = readResponseFunc(sck);
string response = Encoding.ASCII.GetString(dataInByteArray);
Console.WriteLine("res: " + response);
if (response != "make_id" && response != "get_id") { Console.WriteLine(response); }
if (response == "make_id")
{
Console.WriteLine("Someone wants an ID");
byte[] message_1 = Encoding.ASCII.GetBytes(id.ToString());
listOfClient.Add(id);
// START
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
id++;
}
if (response == "get_id")
{
byte[] message_1 = Encoding.ASCII.GetBytes(selected_id.ToString());
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
}
}
catch { if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }; }
}
else if (SocketConnected(sck) == false) { Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
static void SendtoClient(Socket sck)
{
string tempmessage = null;
while (true)
{
if (SocketConnected(sck) == true)
{
if (tempmessage != message)
{
if (!message.Contains("PREVENT_REPETITION_IN_COMMAND"))
{
byte[] message_1 = Encoding.ASCII.GetBytes(message);
sck.Send(Encoding.ASCII.GetBytes(message_1.Length.ToString()));
byte[] responseUnknown = new byte[1];
if (Encoding.ASCII.GetString(responseUnknown) == "a")
{
sck.Send(Encoding.ASCII.GetBytes("b"));
sck.Send(message_1);
}
}
tempmessage = message;
}
}
else if (SocketConnected(sck) == false)
{ Console.WriteLine("Client Disconnected: " + sck.RemoteEndPoint); break; }
}
}
}
}
Problem:
The problem is within the GetSession or the ReadResponseFunc function. The client thinks that his ID received by the server is 'a' (it's suppose to be an integer). I don't want a solution that suggest me to use other libs or
the TcpClient class
Bounty:
I'll put up a bounty with no expiry time to those who solve the problem.
The logic in your code is very confusing. My question to you: Why are you sending 'a' and 'b' back and forth between the server and client? Is it some sort of confirmation that the message has been received?
Anyways, throughout the quick tests I've done just now, it seems that the problem is Line 59 of your server:
sck.Send(Encoding.ASCII.GetBytes("a"));
Here's what I figured out during testing:
Server executes.
Client executes.
Client sends server the length of "make_id" (Line 51 of client)
Client waits for a response to return.
Server reads the value and sends back 'a' (Line 59 of server)
You may want to spend some time to straighten out your protocol so it's less confusing and more organized. That would help people like me and you spot bugs much more easily.
The user 'Bobby' has already found your problem. Credits go to him.
I further suggest that you use less threads, as thread synchronisation needs some effort when doing it right: all data that is accessed from different threads must be secured by locks, so that no outdated values remain in the CPU caches. Use .net Monitor from the "threading synchronisation primitives" for that job.
About the threads themselves:
You should have only one thread in the server. This thread takes all clients from a list (secured by Monitor), in which they were added when connection attempts were received. On each client it checks for incoming messages, evaluates them and replies with own messages if needed.
The client also has just one thread, that will loop (dont forget a sleep in the loop or you will have 100% usage of the used CPU core), send messages when desired and wait for replies when messages were sent.
About the messages:
I already gave some proposals in a comment to Bobby's answer. I suggest you create a CMessage class that has a Serialize() and Deserialze() to create a byte array to send from the CMessage members (serializing the content) or vice versa filling the members from the received bytes. You then may use this class in both programs and you'll have common solution.
So I have managed to retrieve all the IP addresses on my current network. Now I am trying to capture all address that are connecting from each of my networks ip's (Which sites/addresses they visit).
For several of the IP's in my network I am returning this error "Requested address is not valid in its context", but it seems to work fine for my address only.
Currently it is only displaying the sites/addresses I am connecting to on MY PC and not the others.
GOAL: To echo out all addresses that are requested by any of the connected IP's on my network.
Ex:
From [192.168.0.3] To => [52.321.132.2]
From [192.168.0.9] To => [79.21.23.2]
Below is the code I am using, any help would be appreciated!
namespace ConsoleApplication2
{
class Program
{
static CountdownEvent countdown;
static int upCount = 0;
static object lockObj = new object();
const bool resolveNames = true;
static List<string> ADDRESSES = new List<string>();
static void Main(string[] args)
{
#region P_1
countdown = new CountdownEvent(1);
Stopwatch sw = new Stopwatch();
sw.Start();
string ipBase = "192.168.0.";
for (int i = 1; i < 255; i++)
{
string ip = ipBase + i.ToString();
Ping p = new Ping();
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
countdown.AddCount();
p.SendAsync(ip, 100, ip);
}
countdown.Signal();
countdown.Wait();
sw.Stop();
TimeSpan span = new TimeSpan(sw.ElapsedTicks);
Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
#endregion
foreach (String ip in ADDRESSES)
{
IPAddress y = IPAddress.Parse(ip);
try
{
Sniff(y);
}
catch (Exception i)
{
Console.WriteLine("Error for " + y + i.Message);
}
}
Console.Read();
}
static void p_PingCompleted(object sender, PingCompletedEventArgs e)
{
string ip = (string)e.UserState;
if (e.Reply != null && e.Reply.Status == IPStatus.Success)
{
if (resolveNames)
{
string name;
try
{
IPHostEntry hostEntry = Dns.GetHostEntry(ip);
name = hostEntry.HostName;
}
catch (SocketException ex)
{
name = "?";
}
Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
ADDRESSES.Add(ip);
}
else
{
Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
}
lock (lockObj)
{
upCount++;
}
}
else if (e.Reply == null)
{
Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
}
countdown.Signal();
}
static void Sniff(IPAddress ip)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
sck.Bind(new IPEndPoint(ip, 0));
sck.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
sck.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, null);
byte[] buffer = new byte[24];
Action<IAsyncResult> OnReceive = null;
OnReceive = (ar) =>
{
string x = new IPAddress(BitConverter.ToUInt32(buffer, 16)).ToString();
Console.WriteLine("From [" + ip + "] To => " + x, sck.BeginReceive(buffer, 0, 24, SocketFlags.None, new AsyncCallback(OnReceive), null));
};
sck.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
}
}
My code has shown below:
i already setup winpcap too. There arent any problem with programs which used by pcapdotnet
i think problem should be in layers but i dont know very well.
Console.Write("\r IP:Port = ");
string[] answer = Console.ReadLine().Split(':');
//answer[0] = ip , answer[1] = port
Console.WriteLine(answer[0] + "-"+answer[1]);
Attack_Void(answer[0], Convert.ToInt32(answer[1]));
Console.ReadKey();
}
private static void Attack_Void (string ip,int port)
{
try
{
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
PacketDevice selectedDevice = allDevices[0];
Console.WriteLine(selectedDevice.Description);
PacketCommunicator communicator = selectedDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000);
while (true)
{
Thread tret = new Thread(() => Attack_Thread(communicator, ip, port));
tret.Start();
tret.Join();
tret.Abort();
}
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static void Attack_Thread(PacketCommunicator comm,string ip,int port)
{
string rnd_ip = random_ip();
comm.SendPacket(UdpPacket(rnd_ip,ip,port,false,100));
//comm.SendPacket(Udp_Pack_2());
PacketCounter++;
Console.WriteLine("Veriler {0} ip adresine, {1} ip adresinden gönderildi. NO: {2} ",ip,rnd_ip,Convert.ToString(PacketCounter));
}
private static string random_ip()
{
string srcip = rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255) + "." + rnd.Next(0, 255);
return srcip;
}
private static Packet UdpPacket(string src_ip, string rem_ip, int rem_port, bool default_port, int src_port)
{
int port;
if (default_port == true)
{
port = src_port;
} else { port = rnd.Next(0, 65535); }
EthernetLayer ethernetLayer = new EthernetLayer {
Source = new MacAddress("48:E2:44:5E:A8:07"),
Destination = new MacAddress("48:E2:44:5E:A8:07") };
IpV4Layer ipv4Layer = new IpV4Layer
{
// Source = new IpV4Address(src_ip),
Source = new IpV4Address("127.0.0.1"),
CurrentDestination = new IpV4Address(rem_ip),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort = (ushort)port,
DestinationPort = (ushort)rem_port, //port
Checksum = null,
CalculateChecksumValue = true,
};
PayloadLayer payloadLayer =
new PayloadLayer
{
Data = new Datagram(new byte[] { 0x28 }),
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipv4Layer, udpLayer, payloadLayer);
return builder.Build(DateTime.Now);
}
These are my code i actually made a udp server to take packet from this program but i cant send packet.
Also it doesnt give any errors.
And i dont know if my network modem enabled spoofing
Try this but remember it works only with IPv4.
using PcapDotNet.Core;
using PcapDotNet.Core.Extensions;
using PcapDotNet.Packets;
using PcapDotNet.Packets.Ethernet;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace UDP
{
public static class NetworkDevice
{
private static string GetLocalMachineIpAddress()
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
throw new Exception("Network is not available. Please check connection to the internet.");
}
using (Socket socket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
return endPoint.Address.ToString();
}
}
public static PacketDevice GetIpv4PacketDevice()
{
string localMachineIpAddress = GetLocalMachineIpAddress();
IEnumerable<LivePacketDevice> ipV4adapters = LivePacketDevice.AllLocalMachine.Where(w =>
(w.Addresses.Select(s => s.Address.Family))
.Contains(SocketAddressFamily.Internet));
foreach (var adapter in ipV4adapters)
{
var adapterAddresses = adapter.Addresses
.Where(w => w.Address.Family == SocketAddressFamily.Internet)
.Select(s => ((IpV4SocketAddress)s.Address).Address.ToString());
if (adapterAddresses.Contains(localMachineIpAddress))
return adapter;
}
throw new ArgumentException("System didn't find any adapter.");
}
}
public static class DefaultGateway
{
private static IPAddress GetDefaultGateway()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up)
.SelectMany(n => n.GetIPProperties()?.GatewayAddresses)
.Select(g => g?.Address)
.FirstOrDefault(a => a != null);
}
private static string GetMacAddressFromResultOfARPcommand(string[] commandResult, string separator)
{
string macAddress = commandResult[3].Substring(Math.Max(0, commandResult[3].Length - 2))
+ separator + commandResult[4] + separator + commandResult[5] + separator + commandResult[6]
+ separator + commandResult[7] + separator
+ commandResult[8].Substring(0, 2);
return macAddress;
}
public static string GetMacAddress(char separator = ':')
{
IPAddress defaultGateway = GetDefaultGateway();
if (defaultGateway == null)
{
throw new Exception("System didn't find the default gateway.");
}
string defaultGatewayIpAddress = defaultGateway.ToString();
return GetMacAddress(defaultGatewayIpAddress, separator);
}
public static string GetMacAddress(string ipAddress, char separator)
{
Process process = new Process();
process.StartInfo.FileName = "arp";
process.StartInfo.Arguments = "-a " + ipAddress;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string strOutput = process.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length <= 8)
{
throw new Exception("System didn't find the default gateway mac address.");
}
return GetMacAddressFromResultOfARPcommand(substrings, separator.ToString());
}
}
public class UdpProcessor
{
private string _destinationMacAddress;
private string _destinationIPAddress;
private ushort _destinationPort;
private string _sourceMacAddress;
private string _sourceIPAddress;
private ushort _sourcePort;
private static LivePacketDevice _device = null;
public UdpProcessor(string destinationIp)
{
_sourcePort = 55555;
_destinationPort = 44444;
_device = NetworkDevice.GetIpv4PacketDevice() as LivePacketDevice;
_destinationIPAddress = destinationIp;
_sourceIPAddress = _device.Addresses[1].Address.ToString().Split(' ')[1]; //todo
_sourceMacAddress = (_device as LivePacketDevice).GetMacAddress().ToString();
_destinationMacAddress = DefaultGateway.GetMacAddress();
}
private EthernetLayer CreateEthernetLayer()
{
return new EthernetLayer
{
Source = new MacAddress(_sourceMacAddress),
Destination = new MacAddress(_destinationMacAddress),
EtherType = EthernetType.None,
};
}
private IpV4Layer CreateIpV4Layer()
{
return new IpV4Layer
{
Source = new IpV4Address(_sourceIPAddress),
CurrentDestination = new IpV4Address(_destinationIPAddress),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null,
Identification = 123,
Options = IpV4Options.None,
Protocol = null,
Ttl = 100,
TypeOfService = 0,
};
}
private UdpLayer CreateUdpLayer()
{
return new UdpLayer
{
SourcePort = _sourcePort,
DestinationPort = _destinationPort,
Checksum = null,
CalculateChecksumValue = true,
};
}
public void SendUDP()
{
EthernetLayer ethernetLayer = CreateEthernetLayer();
IpV4Layer ipV4Layer = CreateIpV4Layer();
UdpLayer udpLayer = CreateUdpLayer();
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer);
using (PacketCommunicator communicator = _device.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.SendPacket(builder.Build(DateTime.Now));
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("\r IP:Port = ");
string ipAddress = Console.ReadLine();
new UdpProcessor(ipAddress).SendUDP();
Console.ReadKey();
}
}
}
Result in wireshark:
I want to get the IP Address and the MAC Address of the user who login to the system (web application).
I am using these to line of codes
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
I am using this method to get the MAC address, but the problem is I am getting the MAC Address of all the Adapters of the computer.
HOW do I know which one is the right one?, how to get the right MAC Address of the device that is connected to my website??
and also how to get the IP of the adapter too.
when i try it on my pc it give 8 adapters with 8 MAC Addresses
I am trying on my pc, I have a wired connection connected to IntraNet, and a wireless connected to internet.
You can never get the MAC address of a user connected to your website, when a socket connection occurs between the destination (your website's server) and a source (client's computer) you can only get the source IP address, for the MAC address it's never sent over the socket connection (Client <--> Server), in order to get the IP address of a user:
using System.Net;
Private string GetIP()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
return addr[addr.Length-1].ToString();
}
source: Here
using System.Runtime.InteropServices;
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
private static string GetClientMAC(string strClientIP) {
string mac_dest = "";
try {
Int32 ldest = inet_addr(strClientIP);
Int32 lhost = inet_addr("");
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
string mac_src = macinfo.ToString("X");
while (mac_src.Length < 12) {
mac_src = mac_src.Insert(0, "0");
}
for (int i = 0; i < 11; i++) {
if (0 == (i % 2)) {
if (i == 10) {
mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
} else {
mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
}
}
}
} catch (Exception err) {
throw new Exception("Lỗi " + err.Message);
}
return mac_dest;
}
This code will help you :)
You can get the MAC address using below code snippet. To implement this function you need to add System.Management namespace in your application. If it is not available you need to add its reference from "Add references" from your project.
using System.Management;
using System.IO;
public string GetMACAddress()
{
string mac_src = "";
string macAddress = "";
foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
{
mac_src += nic.GetPhysicalAddress().ToString();
break;
}
}
while (mac_src.Length < 12)
{
mac_src = mac_src.Insert(0, "0");
}
for (int i = 0; i < 11; i++)
{
if (0 == (i % 2))
{
if (i == 10)
{
macAddress = macAddress.Insert(macAddress.Length, mac_src.Substring(i, 2));
}
else
{
macAddress = macAddress.Insert(macAddress.Length, mac_src.Substring(i, 2)) + "-";
}
}
}
return macAddress;
}
When IIS Deploy this application with code ..run successfully
public string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
private static string GetClientMAC(string strClientIP)
{
string mac_dest = "";
try
{
Int32 ldest = inet_addr(strClientIP);
Int32 lhost = inet_addr("");
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
string mac_src = macinfo.ToString("X");
while (mac_src.Length < 12)
{
mac_src = mac_src.Insert(0, "0");
}
for (int i = 0; i < 11; i++)
{
if (0 == (i % 2))
{
if (i == 10)
{
mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
}
else
{
mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
}
}
}
}
catch (Exception err)
{
throw new Exception("Lỗi " + err.Message);
}
return mac_dest;
}
protected void Button1_Click1(object sender, EventArgs e)
{
Label1.Text = GetClientMAC(GetIPAddress());
}
MAC Addresses cannot be accessed by .NET, neither by JS applications.
The MAC address it's never sent over the socket connection, only the IP Address, so you can only get the IP, with the following code:
public string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
First of all, would be nice to know why do you want the MAC Address of your clients (users) as Mac Addresses are NOT UNIQUE.
You can only use the .NET Framework to get the SERVER Connection, and never the User it self, for that, for getting the client MAC Address you can only rely on javascript and ActiveX control, witch can only be used on Internet Explorer as Firefox already deprecated it's support to ActiveX controls several years ago.
A good read about this can be found in this article.
I am running a server, and I want to display my own IP address.
What is the syntax for getting the computer's own (if possible, external) IP address?
Someone wrote the following code.
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?
Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.
Edit: The only thing I would change would be to change this:
if (ip.AddressFamily.ToString() == "InterNetwork")
to this:
if (ip.AddressFamily == AddressFamily.InterNetwork)
There is no need to ToString an enumeration for comparison.
The only way to know your public IP is to ask someone else to tell you; this code may help you:
public string GetPublicIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
Cleaner and an all in one solution :D
//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:
The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.
This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.
If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:
Filter out any NetworkInterfaces that are inactive by checking for OperationalStatus == OperationalStatus.Up. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.
For each NetworkInterface, you can get an IPInterfaceProperties object using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses property for a list of UnicastIPAddressInformation objects.
Filter out non-preferred unicast addresses by checking for DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
Filter out "virtual" addresses by checking for AddressPreferredLifetime != UInt32.MaxValue.
At this point I take the address of the first (if any) unicast address that matches all of these filters.
EDIT:
[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]
The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.
static IEnumerable<IPAddress> GetLocalIpAddresses()
{
// Get the list of network interfaces for the local computer.
var adapters = NetworkInterface.GetAllNetworkInterfaces();
// Return the list of local IPv4 addresses excluding the local
// host, disconnected, and virtual addresses.
return (from adapter in adapters
let properties = adapter.GetIPProperties()
from address in properties.UnicastAddresses
where adapter.OperationalStatus == OperationalStatus.Up &&
address.Address.AddressFamily == AddressFamily.InterNetwork &&
!address.Equals(IPAddress.Loopback) &&
address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
address.AddressPreferredLifetime != UInt32.MaxValue
select address.Address);
}
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
Just tested this on my machine and it works.
If you want to avoid using DNS:
List<IPAddress> ipList = new List<IPAddress>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (var address in netInterface.GetIPProperties().UnicastAddresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine("found IP " + address.Address.ToString());
ipList.Add(address.Address);
}
}
}
Don't rely on InterNetwork all the time because you can have more than one device which also uses IP4 which would screw up the results in getting your IP.
Now, if you would like you may just copy this and please review it or update it to how you see fit.
First I get the address of the router (gateway)
If it comes back that I am connected to a gateway (which mean not connected directly into the modem wireless or not) then we have our gateway address as IPAddress else we a null pointer IPAddress reference.
Then we need to get the computer's list of IPAddresses. This is where things are not that hard because routers (all routers) use 4 bytes (...). The first three are the most important because any computer connected to it will have the IP4 address matching the first three bytes. Ex: 192.168.0.1 is standard for router default IP unless changed by the adminstrator of it. '192.168.0' or whatever they may be is what we need to match up. And that is all I did in IsAddressOfGateway function.
The reason for the length matching is because not all addresses (which are for the computer only) have the length of 4 bytes. If you type in netstat in the cmd, you will find this to be true. So there you have it. Yes, it takes a little more work to really get what you are looking for. Process of elimination.
And for God's sake, do not find the address by pinging it which takes time because first you are sending the address to be pinged and then it has to send the result back. No, work directly with .Net classes which deal with your system environment and you will get the answers you are looking for when it has to solely do with your computer.
Now if you are directly connected to your modem, the process is almost the same because the modem is your gateway but the submask is not the same because your getting the information directly from your DNS Server via modem and not masked by the router serving up the Internet to you although you still can use the same code because the last byte of the IP assigned to the modem is 1. So if IP sent from the modem which does change is 111.111.111.1' then you will get 111.111.111.(some byte value). Keep in mind the we need to find the gateway information because there are more devices which deal with internet connectivity than your router and modem.
Now you see why you DON'T change your router's first two bytes 192 and 168. These are strictly distinguished for routers only and not internet use or we would have a serious issue with IP Protocol and double pinging resulting in crashing your computer. Image that your assigned router IP is 192.168.44.103 and you click on a site with that IP as well. OMG! Your computer would not know what to ping. Crash right there. To avoid this issue, only routers are assigned these and not for internet usage. So leave the first two bytes of the router alone.
static IPAddress FindLanAddress()
{
IPAddress gateway = FindGetGatewayAddress();
if (gateway == null)
return null;
IPAddress[] pIPAddress = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in pIPAddress) {
if (IsAddressOfGateway(address, gateway))
return address;
return null;
}
static bool IsAddressOfGateway(IPAddress address, IPAddress gateway)
{
if (address != null && gateway != null)
return IsAddressOfGateway(address.GetAddressBytes(),gateway.GetAddressBytes());
return false;
}
static bool IsAddressOfGateway(byte[] address, byte[] gateway)
{
if (address != null && gateway != null)
{
int gwLen = gateway.Length;
if (gwLen > 0)
{
if (address.Length == gateway.Length)
{
--gwLen;
int counter = 0;
for (int i = 0; i < gwLen; i++)
{
if (address[i] == gateway[i])
++counter;
}
return (counter == gwLen);
}
}
}
return false;
}
static IPAddress FindGetGatewayAddress()
{
IPGlobalProperties ipGlobProps = IPGlobalProperties.GetIPGlobalProperties();
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipInfProps = ni.GetIPProperties();
foreach (GatewayIPAddressInformation gi in ipInfProps.GatewayAddresses)
return gi.Address;
}
return null;
}
I just thought that I would add my own, one-liner (even though there are many other useful answers already).
string ipAddress = new WebClient().DownloadString("http://icanhazip.com");
For getting the current public IP address, all you need to do is create an ASPX page with the following line on the page load event:
Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
If you are running in intranet you'll be able to get local machine IP address and if not you'll get external ip address with this:
Web:
//this will bring the IP for the current machine on browser
System.Web.HttpContext.Current.Request.UserHostAddress
Desktop:
//This one will bring all local IPs for the desired namespace
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
namespace NKUtilities
{
using System;
using System.Net;
using System.Net.Sockets;
public class DNSUtility
{
public static int Main(string [] args)
{
string strHostName = "";
try {
if(args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
// Otherwise, get the IP address of the host provided on the command line.
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for(int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
return 0;
}
catch(SocketException se)
{
Console.WriteLine("{0} ({1})", se.Message, strHostName);
return -1;
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}.", ex.Message);
return -1;
}
}
}
}
Look here for details.
You have to remember your computer can have more than one IP (actually it always does) - so which one are you after.
Try this:
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
String MyIp = localIPs[0].ToString();
Maybe by external IP you can consider (if you are in a Web server context) using this
Request.ServerVariables["LOCAL_ADDR"];
I was asking the same question as you and I found it in this stackoverflow article.
It worked for me.
namespace NKUtilities
{
using System;
using System.Net;
public class DNSUtility
{
public static int Main (string [] args)
{
String strHostName = new String ("");
if (args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName ();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
}
return 0;
}
}
}
using System;
using System.Net;
namespace IPADDRESS
{
class Program
{
static void Main(string[] args)
{
String strHostName = string.Empty;
if (args.Length == 0)
{
/* First get the host name of local machine.*/
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
/* Then using host name, get the IP address list..*/
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
}
}
}
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
Simple single line of code that returns the first internal IPV4 address or null if there are none. Added as a comment above, but may be useful to someone (some solutions above will return multiple addresses that need further filtering).
It's also easy to return loopback instead of null I guess with:
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork) ?? new IPAddress( new byte[] {127, 0, 0, 1} );
To find IP address list I have used this solution
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
But I personally like below solution to get local valid IP address
public static IPAddress GetIPAddress(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
public static void Main()
{
Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
Console.WriteLine("Google IP:" + GetIPAddress("google.com");
Console.ReadLine();
}
The LINQ solution:
Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.
private string FetchIP()
{
//Get all IP registered
List<string> IPList = new List<string>();
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
IPList.Add(ip.ToString());
}
}
//Find the first IP which is not only local
foreach (string a in IPList)
{
Ping p = new Ping();
string[] b = a.Split('.');
string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
PingReply t = p.Send(ip2);
p.Dispose();
if (t.Status == IPStatus.Success && ip2 != a)
{
return a;
}
}
return null;
}
The question doesn't say ASP.NET MVC but I'm just leaving this here anyway:
Request.UserHostAddress
Get all IP addresses as strings using LINQ:
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
...
string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(d=>d.Address.ToString())
).ToArray();
TO FILTER OUT PRIVATE ONES...
First, define an extension method IsPrivate():
public static class IPAddressExtensions
{
// Collection of private CIDRs (IpAddress/Mask)
private static Tuple<int, int>[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
.Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
.Parse(c.Split('/')[0]).GetAddressBytes(), 0)
, IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
.ToArray();
public static bool IsPrivate(this IPAddress ipAddress)
{
int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));
}
}
... And then use it to filter out private IPs:
string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(c=>c.GetIPProperties().UnicastAddresses
.Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
&& !d.Address.IsPrivate() // Filter out private ones
)
.Select(d=>d.Address.ToString())
).ToArray();
It works for me... and should be faster in most case (if not all) than querying a DNS server. Thanks to Dr. Wily's Apprentice (here).
// ************************************************************************
/// <summary>
/// Will search for the an active NetworkInterafce that has a Gateway, otherwise
/// it will fallback to try from the DNS which is not safe.
/// </summary>
/// <returns></returns>
public static NetworkInterface GetMainNetworkInterface()
{
List<NetworkInterface> candidates = new List<NetworkInterface>();
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (
NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
candidates.Add(ni);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
// Accoring to our tech, the main NetworkInterface should have a Gateway
// and it should be the ony one with a gateway.
if (candidates.Count > 1)
{
for (int n = candidates.Count - 1; n >= 0; n--)
{
if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
{
candidates.RemoveAt(n);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
}
// Fallback to try by getting my ipAdress from the dns
IPAddress myMainIpAdress = null;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
{
myMainIpAdress = ip;
break;
}
}
if (myMainIpAdress != null)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.Address.Equals(myMainIpAdress))
{
return ni;
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// AddressFamily.InterNetwork = IPv4
/// Thanks to Dr. Wilys Apprentice at
/// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
/// using System.Net.NetworkInformation;
/// </summary>
/// <param name="mac"></param>
/// <param name="addressFamily">AddressFamily.InterNetwork = IPv4, AddressFamily.InterNetworkV6 = IPv6</param>
/// <returns></returns>
public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.GetPhysicalAddress().Equals(mac))
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
{
if (ai.Address.AddressFamily == addressFamily)
{
return ai.Address;
}
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call
/// '?.ToString() ?? ""' on the result.
/// </summary>
/// <returns></returns>
public static IPAddress GetMyInternetIpAddress()
{
NetworkInterface ni = GetMainNetworkInterface();
IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
if (ipAddress == null) // could it be possible ?
{
ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
}
return ipAddress;
}
// ******************************************************************
Just as reference this is the full class code where I defined it:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace TcpMonitor
{
/*
Usage:
var cons = TcpHelper.GetAllTCPConnections();
foreach (TcpHelper.MIB_TCPROW_OWNER_PID c in cons) ...
*/
public class NetHelper
{
[DllImport("iphlpapi.dll", SetLastError = true)]
static extern uint GetExtendedUdpTable(IntPtr pUdpTable, ref int dwOutBufLen, bool sort, int ipVersion, UDP_TABLE_CLASS tblClass, uint reserved = 0);
public enum UDP_TABLE_CLASS
{
UDP_TABLE_BASIC,
UDP_TABLE_OWNER_PID,
UDP_TABLE_OWNER_MODULE
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDPROW_OWNER_PID
{
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_UDP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_UDP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr, localScopeId); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
}
public static List<MIB_UDPROW_OWNER_PID> GetAllUDPConnections()
{
return GetUDPConnections<MIB_UDPROW_OWNER_PID, MIB_UDPTABLE_OWNER_PID> (AF_INET);
}
public static List<MIB_UDP6ROW_OWNER_PID> GetAllUDPv6Connections()
{
return GetUDPConnections<MIB_UDP6ROW_OWNER_PID, MIB_UDP6TABLE_OWNER_PID>(AF_INET6);
}
private static List<IPR> GetUDPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
{
List<IPR> result = null;
IPR[] tableRows = null;
int buffSize = 0;
var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
// how much memory do we need?
uint ret = GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
IntPtr udpTablePtr = Marshal.AllocHGlobal(buffSize);
try
{
ret = GetExtendedUdpTable(udpTablePtr, ref buffSize, true, ipVersion, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID);
if (ret != 0)
return new List<IPR>();
// get the number of entries in the table
IPT table = (IPT)Marshal.PtrToStructure(udpTablePtr, typeof(IPT));
int rowStructSize = Marshal.SizeOf(typeof(IPR));
uint numEntries = (uint)dwNumEntriesField.GetValue(table);
// buffer we will be returning
tableRows = new IPR[numEntries];
IntPtr rowPtr = (IntPtr)((long)udpTablePtr + 4);
for (int i = 0; i < numEntries; i++)
{
IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
tableRows[i] = tcpRow;
rowPtr = (IntPtr)((long)rowPtr + rowStructSize); // next entry
}
}
finally
{
result = tableRows?.ToList() ?? new List<IPR>();
// Free the Memory
Marshal.FreeHGlobal(udpTablePtr);
}
return result;
}
[DllImport("iphlpapi.dll", SetLastError = true)]
static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass, uint reserved = 0);
public enum MIB_TCP_STATE
{
MIB_TCP_STATE_CLOSED = 1,
MIB_TCP_STATE_LISTEN = 2,
MIB_TCP_STATE_SYN_SENT = 3,
MIB_TCP_STATE_SYN_RCVD = 4,
MIB_TCP_STATE_ESTAB = 5,
MIB_TCP_STATE_FIN_WAIT1 = 6,
MIB_TCP_STATE_FIN_WAIT2 = 7,
MIB_TCP_STATE_CLOSE_WAIT = 8,
MIB_TCP_STATE_CLOSING = 9,
MIB_TCP_STATE_LAST_ACK = 10,
MIB_TCP_STATE_TIME_WAIT = 11,
MIB_TCP_STATE_DELETE_TCB = 12
}
public enum TCP_TABLE_CLASS
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCPROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6TABLE_OWNER_PID
{
public uint dwNumEntries;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 1)]
public MIB_TCP6ROW_OWNER_PID[] table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public uint state;
public uint localAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
public uint remoteAddr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr); }
}
public ushort LocalPort
{
get
{
return BitConverter.ToUInt16(new byte[2] { localPort[1], localPort[0] }, 0);
}
}
public IPAddress RemoteAddress
{
get { return new IPAddress(remoteAddr); }
}
public ushort RemotePort
{
get
{
return BitConverter.ToUInt16(new byte[2] { remotePort[1], remotePort[0] }, 0);
}
}
public MIB_TCP_STATE State
{
get { return (MIB_TCP_STATE)state; }
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCP6ROW_OWNER_PID
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] localAddr;
public uint localScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] localPort;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] remoteAddr;
public uint remoteScopeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] remotePort;
public uint state;
public uint owningPid;
public uint ProcessId
{
get { return owningPid; }
}
public long LocalScopeId
{
get { return localScopeId; }
}
public IPAddress LocalAddress
{
get { return new IPAddress(localAddr, LocalScopeId); }
}
public ushort LocalPort
{
get { return BitConverter.ToUInt16(localPort.Take(2).Reverse().ToArray(), 0); }
}
public long RemoteScopeId
{
get { return remoteScopeId; }
}
public IPAddress RemoteAddress
{
get { return new IPAddress(remoteAddr, RemoteScopeId); }
}
public ushort RemotePort
{
get { return BitConverter.ToUInt16(remotePort.Take(2).Reverse().ToArray(), 0); }
}
public MIB_TCP_STATE State
{
get { return (MIB_TCP_STATE)state; }
}
}
public const int AF_INET = 2; // IP_v4 = System.Net.Sockets.AddressFamily.InterNetwork
public const int AF_INET6 = 23; // IP_v6 = System.Net.Sockets.AddressFamily.InterNetworkV6
public static Task<List<MIB_TCPROW_OWNER_PID>> GetAllTCPConnectionsAsync()
{
return Task.Run(() => GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET));
}
public static List<MIB_TCPROW_OWNER_PID> GetAllTCPConnections()
{
return GetTCPConnections<MIB_TCPROW_OWNER_PID, MIB_TCPTABLE_OWNER_PID>(AF_INET);
}
public static Task<List<MIB_TCP6ROW_OWNER_PID>> GetAllTCPv6ConnectionsAsync()
{
return Task.Run(()=>GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6));
}
public static List<MIB_TCP6ROW_OWNER_PID> GetAllTCPv6Connections()
{
return GetTCPConnections<MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID>(AF_INET6);
}
private static List<IPR> GetTCPConnections<IPR, IPT>(int ipVersion)//IPR = Row Type, IPT = Table Type
{
List<IPR> result = null;
IPR[] tableRows = null;
int buffSize = 0;
var dwNumEntriesField = typeof(IPT).GetField("dwNumEntries");
// how much memory do we need?
uint ret = GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
IntPtr tcpTablePtr = Marshal.AllocHGlobal(buffSize);
try
{
ret = GetExtendedTcpTable(tcpTablePtr, ref buffSize, true, ipVersion, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);
if (ret != 0)
return new List<IPR>();
// get the number of entries in the table
IPT table = (IPT)Marshal.PtrToStructure(tcpTablePtr, typeof(IPT));
int rowStructSize = Marshal.SizeOf(typeof(IPR));
uint numEntries = (uint)dwNumEntriesField.GetValue(table);
// buffer we will be returning
tableRows = new IPR[numEntries];
IntPtr rowPtr = (IntPtr)((long)tcpTablePtr + 4);
for (int i = 0; i < numEntries; i++)
{
IPR tcpRow = (IPR)Marshal.PtrToStructure(rowPtr, typeof(IPR));
tableRows[i] = tcpRow;
rowPtr = (IntPtr)((long)rowPtr + rowStructSize); // next entry
}
}
finally
{
result = tableRows?.ToList() ?? new List<IPR>();
// Free the Memory
Marshal.FreeHGlobal(tcpTablePtr);
}
return result;
}
public static string GetTcpStateName(MIB_TCP_STATE state)
{
switch (state)
{
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSED:
return "Closed";
case MIB_TCP_STATE.MIB_TCP_STATE_LISTEN:
return "Listen";
case MIB_TCP_STATE.MIB_TCP_STATE_SYN_SENT:
return "SynSent";
case MIB_TCP_STATE.MIB_TCP_STATE_SYN_RCVD:
return "SynReceived";
case MIB_TCP_STATE.MIB_TCP_STATE_ESTAB:
return "Established";
case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT1:
return "FinWait 1";
case MIB_TCP_STATE.MIB_TCP_STATE_FIN_WAIT2:
return "FinWait 2";
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSE_WAIT:
return "CloseWait";
case MIB_TCP_STATE.MIB_TCP_STATE_CLOSING:
return "Closing";
case MIB_TCP_STATE.MIB_TCP_STATE_LAST_ACK:
return "LastAck";
case MIB_TCP_STATE.MIB_TCP_STATE_TIME_WAIT:
return "TimeWait";
case MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB:
return "DeleteTCB";
default:
return ((int)state).ToString();
}
}
private static readonly ConcurrentDictionary<string, string> DicOfIpToHostName = new ConcurrentDictionary<string, string>();
public const string UnknownHostName = "Unknown";
// ******************************************************************
public static string GetHostName(IPAddress ipAddress)
{
return GetHostName(ipAddress.ToString());
}
// ******************************************************************
public static string GetHostName(string ipAddress)
{
string hostName = null;
if (!DicOfIpToHostName.TryGetValue(ipAddress, out hostName))
{
try
{
if (ipAddress == "0.0.0.0" || ipAddress == "::")
{
hostName = ipAddress;
}
else
{
hostName = Dns.GetHostEntry(ipAddress).HostName;
}
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
hostName = UnknownHostName;
}
DicOfIpToHostName[ipAddress] = hostName;
}
return hostName;
}
// ************************************************************************
/// <summary>
/// Will search for the an active NetworkInterafce that has a Gateway, otherwise
/// it will fallback to try from the DNS which is not safe.
/// </summary>
/// <returns></returns>
public static NetworkInterface GetMainNetworkInterface()
{
List<NetworkInterface> candidates = new List<NetworkInterface>();
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (
NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
candidates.Add(ni);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
// Accoring to our tech, the main NetworkInterface should have a Gateway
// and it should be the ony one with a gateway.
if (candidates.Count > 1)
{
for (int n = candidates.Count - 1; n >= 0; n--)
{
if (candidates[n].GetIPProperties().GatewayAddresses.Count == 0)
{
candidates.RemoveAt(n);
}
}
if (candidates.Count == 1)
{
return candidates[0];
}
}
// Fallback to try by getting my ipAdress from the dns
IPAddress myMainIpAdress = null;
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork) // Get the first IpV4
{
myMainIpAdress = ip;
break;
}
}
if (myMainIpAdress != null)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.Address.Equals(myMainIpAdress))
{
return ni;
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// AddressFamily.InterNetwork = IPv4
/// Thanks to Dr. Wilys Apprentice at
/// http://stackoverflow.com/questions/1069103/how-to-get-the-ip-address-of-the-server-on-which-my-c-sharp-application-is-runni
/// using System.Net.NetworkInformation;
/// </summary>
/// <param name="mac"></param>
/// <param name="addressFamily">AddressFamily.InterNetwork = IPv4, AddressFamily.InterNetworkV6 = IPv6</param>
/// <returns></returns>
public static IPAddress GetIpFromMac(PhysicalAddress mac, AddressFamily addressFamily = AddressFamily.InterNetwork)
{
NetworkInterface[] NetworkInterfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in NetworkInterfaces)
{
if (ni.GetPhysicalAddress().Equals(mac))
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPInterfaceProperties props = ni.GetIPProperties();
foreach (UnicastIPAddressInformation ai in props.UnicastAddresses)
{
if (ai.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
{
if (ai.Address.AddressFamily == addressFamily)
{
return ai.Address;
}
}
}
}
}
}
return null;
}
// ******************************************************************
/// <summary>
/// Return the best guess of main ipAdress. To get it in the form aaa.bbb.ccc.ddd just call
/// '?.ToString() ?? ""' on the result.
/// </summary>
/// <returns></returns>
public static IPAddress GetMyInternetIpAddress()
{
NetworkInterface ni = GetMainNetworkInterface();
IPAddress ipAddress = GetIpFromMac(ni.GetPhysicalAddress());
if (ipAddress == null) // could it be possible ?
{
ipAddress = GetIpFromMac(ni.GetPhysicalAddress(), AddressFamily.InterNetworkV6);
}
return ipAddress;
}
// ******************************************************************
public static bool IsBroadcastAddress(IPAddress ipAddress)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
return ipAddress.GetAddressBytes()[3] == 255;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return false; // NO broadcast in IPv6
}
return false;
}
// ******************************************************************
public static bool IsMulticastAddress(IPAddress ipAddress)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
// Source: https://technet.microsoft.com/en-us/library/cc772041(v=ws.10).aspx
return ipAddress.GetAddressBytes()[0] >= 224 && ipAddress.GetAddressBytes()[0] <= 239;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
return ipAddress.IsIPv6Multicast;
}
return false;
}
// ******************************************************************
}
}
Yet another way to get your public IP address is to use OpenDNS's resolve1.opendns.com server with myip.opendns.com as the request.
On the command line this is:
nslookup myip.opendns.com resolver1.opendns.com
Or in C# using the DNSClient nuget:
var lookup = new LookupClient(new IPAddress(new byte[] { 208, 67, 222, 222 }));
var result = lookup.Query("myip.opendns.com", QueryType.ANY);
This is a bit cleaner than hitting http endpoints and parsing responses.
And this is to get all local IPs in csv format in VB.NET
Imports System.Net
Imports System.Net.Sockets
Function GetIPAddress() As String
Dim ipList As List(Of String) = New List(Of String)
Dim host As IPHostEntry
Dim localIP As String = "?"
host = Dns.GetHostEntry(Dns.GetHostName())
For Each ip As IPAddress In host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
localIP = ip.ToString()
ipList.Add(localIP)
End If
Next
Dim ret As String = String.Join(",", ipList.ToArray)
Return ret
End Function
To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.
The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.
public static string GetIP()
{
string externalIP = "";
externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.
public static WebClient webclient = new WebClient();
public static string GetIP()
{
string externalIP = "";
externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
.Matches(externalIP)[0].ToString();
return externalIP;
}
private static string GetLocalIpAdresse()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach(var ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception ("No network adapters with an IPv4 address in the system");
}