How I can convert ip to url? I want to create sniffer where user can see at the end of day list of sites and total time that he spend on the each site
static void Sniff(IPAddress ip)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
//sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
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) =>
{
Console.WriteLine(
"{0}\t{1}:{2}\t===>\t{3}:{4}"
, buffer.Skip(9).First().ToProtocolString()
, new IPAddress(BitConverter.ToUInt32(buffer, 12)).ToString()
, ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 20))).ToString()
, new IPAddress(BitConverter.ToUInt32(buffer, 16)).ToString()
, ((ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 22))).ToString());
buffer = new byte[24];
sck.BeginReceive(buffer, 0, 24, SocketFlags.None,
new AsyncCallback(OnReceive), null);
};
sck.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(OnReceive), null);
}
public static string ToProtocolString(this byte b)
{
switch (b)
{
case 1: return "ICMP";
case 6: return "TCP";
case 17: return "UDP";
default: return "#" + b.ToString();
}
}
As BugFinder mentioned below your question: It is not as simple as finding the IP address to know what website a user is visiting. A single IP address can host multiple websites and there is no telling what website it is the one the user of the computer is visiting (unless you use a proxy, monitor the web requests or something like that).
In case knowing the host name is enough: You could use the DNS object in C#. For example:
static void Main(string[] args) { string ip = "8.8.8.8"; Console.WriteLine(Dns.GetHostEntry(ip).HostName); //prints the host name Console.ReadKey(); }
Will give the following output in the console:
google-public-dns-a.google.com
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.