兩個擷取http頁面的c#函數)

來源:互聯網
上載者:User

 http://www.szasp.net/Blog/ShowSource.asp?NewsId=1510

埋頭苦幹一天終於搞定!一個用C#寫的windows應用程式,作用嘛,就是對asp程式已知的20種漏洞進行掃描,顯示來源程式。在這個應用程式中用到兩種獲得http頁面的方法,一種是直接用httpwebrequest類,而另一種是同伺服器通過tcp/ip建立socket串連,直接查詢連接埠80 , 為此我寫了以下兩個函數,第一個比較簡單,參數只有一個,就是要求的url , 另外一個比較複雜,也很通用,不僅可以請求http頁面,還可以和其他連接埠通訊,如連接埠43的whois,連接埠25的smtp,連接埠21的ftp甚至pop3等等,三個參數分別是主機名稱,請求命令和連接埠。好了,看程式吧。

//擷取http頁面函數
private string Get_Http(string a_strUrl)
{
string strResult ;
HttpWebRequest myReq = (HttpWebRequest)
WebRequestFactory.Create(a_strUrl) ;

try
{
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream () ;

StreamReader sr = new StreamReader(myStream , Encoding.Default);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine()+"\r\n");
}

strResult = strBuilder.ToString();
}
catch(Exception exp)
{
strResult = "錯誤:" + exp.Message ;
}

return strResult ;

}

//通過同server建立tcp/ip串連,發送socket命令
private string Get_Socket_Request(string a_strServer , string a_strRequest , Int32 a_intPort)
{
//Set up variables and String to write to the server
Encoding ASCII = Encoding.Default ;
string Get = a_strRequest + "Connection: Close\r\n\r\n";
//string Get =
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;

// IPAddress and IPEndPoint represent the endpoint that will
// receive the request
IPAddress hostadd = DNS.Resolve(a_strServer.Substring(7 ,a_strServer.Length - 7));
IPEndPoint EPhost = new IPEndPoint(hostadd, a_intPort);

//Create the Socket for sending data over TCP
Socket s = new Socket(AddressFamily.AfINet, SocketType.SockStream,
ProtocolType.ProtTCP );

// Connect to host using IPEndPoint
if (s.Connect(EPhost) != 0)
{
strRetPage = "Unable to connect to host";
return strRetPage;
}

// Sent the GET text to the host
s.Send(ByteGet, ByteGet.Length, 0);

// Receive the page, loop until all bytes are received
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}

return strRetPage ;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.