如何将ip转换为url?我想创建嗅探器,用户可以在每天结束时查看网站列表和他在每个网站上花费的总时间
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();
}
}
答案 0 :(得分:0)
正如BugFinder在下面提到的那样你的问题:它并不像找到IP地址那样简单,无法知道用户正在访问哪个网站。单个IP地址可以托管多个网站,并且无法确定计算机用户正在访问的网站(除非您使用代理,监控Web请求或类似的内容)。
如果知道主机名就足够了:您可以在C#中使用DNS对象。例如:
static void Main(string[] args)
{
string ip = "8.8.8.8";
Console.WriteLine(Dns.GetHostEntry(ip).HostName); //prints the host name
Console.ReadKey();
}
将在控制台中提供以下输出:
google-public-dns-a.google.com