C#使用SOCKET获取ASPSESSIONID、PHPSESSID等Cookie
简单写了一个小类,获取ASPSESSIONID、PHPSESSID等WebClient无法获取的Cookies,如果高手有更好的意见,欢迎补充。
代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Net; 5 using System.Net.Sockets; 6 7 namespace EatOrange 8 { 9 // 使用SOCKET获取Cookie信息 10 class CookieGet 11 { 12 private Socket socket; 13 14 public string GetCookie(string strHost, string strGet, string strReferer) 15 { 16 IPEndPoint hostEndPoint; 17 IPAddress[] hostAddresses; 18 StringBuilder stringBuilder = new StringBuilder(); 19 byte[] byteSend; 20 21 // 首先构造HTTP请求头 22 stringBuilder.Append("GET " + strGet + " HTTP/1.1\r\n"); 23 stringBuilder.Append("Accept: */*\r\n"); 24 stringBuilder.Append("Referer: " + strReferer + "\r\n"); 25 stringBuilder.Append("Accept-Language: zh-CN\r\n"); 26 stringBuilder.Append("User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"); 27 stringBuilder.Append("Host: " + strHost + "\r\n"); 28 stringBuilder.Append("Connection: Keep-Alive\r\n\r\n"); 29 30 byteSend = System.Text.Encoding.ASCII.GetBytes(stringBuilder.ToString()); 31 32 // 利用SOCKET发送HTTP协议 33 int conPort = 80; 34 35 // 获取DNS服务器信息 36 hostAddresses = Dns.GetHostAddresses(strHost); 37 38 // 给每个IP发送get请求(因为一个域名可能对应多个IP地址) 39 foreach (IPAddress addr in hostAddresses) 40 { 41 hostEndPoint = new IPEndPoint(addr, conPort); 42 43 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 44 socket.Connect(hostEndPoint); 45 46 if (socket.Connected) 47 { 48 socket.Send(byteSend, byteSend.Length, 0); 49 } 50 } 51 // 获取服务器的返回信息 52 Byte[] byteReceive = new Byte[1024]; 53 Int32 bytes = socket.Receive(byteReceive); 54 55 string str = Encoding.Default.GetString(byteReceive, 0, bytes); 56 57 // 获取Cookie信息 58 59 int pos1, pos2; 60 pos1 = str.IndexOf("Set-Cookie: ") + 12; // 12 is the length of "Set-Cookie: " 61 62 if (pos1 == -1) 63 return "<Error>Not Found</Error>"; 64 65 pos2 = str.IndexOf("\r\n", pos1); 66 67 return str.Substring(pos1, pos2 - pos1); 68 } 69 } 70 }