关于web应用程序安全的思考(一)
2008-11-26 13:35:59 来源:WEB开发网相信大家基本上能理解上述字符串的意义。这表明我们只要组织类似的字符串﹐然后发往相应的web服务器﹐就可以请求到某个URL了﹐也就是说web请求不依赖浏览器(其实web也不依赖服务器﹐它只依赖http协议)。
下面的这个程序是C#写的通过socket直接向web服务器发送http请求的示例﹕
1using System;
2using System.Text;
3using System.IO;
4using System.Net;
5using System.Net.Sockets;
6
7public class server
8{
9 //建立socket连接
10 private static Socket ConnectSocket(string server, int port)
11 {
12 Socket s = null;
13 IPHostEntry hostEntry = null;
14 hostEntry = Dns.GetHostEntry(server);
15 foreach (IPAddress address in hostEntry.AddressList)
16 {
17 IPEndPoint ipe = new IPEndPoint(address, port);
18 Socket tempSocket =
19 new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
20 tempSocket.Connect(ipe);
21 if (tempSocket.Connected)
22 {
23 s = tempSocket;
24 break;
25 }
26 else
27 {
28 continue;
29 }
30 }
31 Console.WriteLine(s==null?"":"连接建立成功﹗");
32 return s;
33 }
34
35 //发送request请求并返回响应字串
36 private static string SocketSendReceive(string request,string server, int port)
37 {
38 Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
39 Byte[] bytesReceived = new Byte[256];
40 Socket s = ConnectSocket(server, port);
41 if (s == null)
42 return ("连接失败﹗");
43 Console.WriteLine("正在发送请求");
44 s.Send(bytesSent, bytesSent.Length, 0);
45 int bytes = 0;
46 StringBuilder responsestr = new StringBuilder();
47 Console.WriteLine("正在接收web服务器的回应");
48 do
49 {
50 bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
51 responsestr.Append(Encoding.UTF8.GetString(bytesReceived, 0, bytes));
52 }
53 while (bytes > 0);
54 return responsestr.ToString();
55 }
56
57 //获取Request请求字符串
58 private static string getRequestStr()
59 {
60 StringBuilder sb = new StringBuilder();
61 sb.Append("GET /FrameWorkService/TestRequest.aspx?name=zkw&age=24 HTTP/1.1rn");
62 sb.Append("Host: localhostrn");
63 sb.Append("Accept: */*rn");
64 sb.Append("Accept-Encoding: gzip, deflatern");
65 sb.Append("Accept-Language: zh-twrn");
66 sb.Append("User-Agent: Mozilla/8.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)rn");
67 sb.Append("UA-CPU: x86rn");
68 sb.Append("Cookie: ASP.NET_SessionId=g5vz3k55q4dhgy3dvmm3dj4xrn");
69 sb.Append("Connection: Closernrn");
70 return sb.ToString();
71 }
72
73 public static void Main(string[] args)
74 {
75 string requeststr = getRequestStr();
76 Console.WriteLine("请求字串如下﹕n{0}",requeststr);
77 string result = SocketSendReceive(requeststr,"localhost",80);
78 Console.WriteLine(result);
79 Console.ReadLine();
80 }
81}
更多精彩
赞助商链接