SoFunction
Updated on 2025-03-07

Code to use Socket to obtain web page source code in C#


using System;
using ;
using ;

namespace ConsoleApplication1
{
class WebToolkit
{
/// <summary>
/// Url structure
/// </summary>
struct UrlInfo
{
public string Host;
public int Port;
public string File;
public string Body;
}

/// <summary>
/// parse URL
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static UrlInfo ParseURL(string url)
{
UrlInfo urlInfo = new UrlInfo();
string[] strTemp = null;
= "";
= 80;
= "/";
= "";
int intIndex = ().IndexOf("http://");
if (intIndex != -1)
{
url = (7);
intIndex = ("/");
if (intIndex == -1)
{
= url;
}
else
{
= (0, intIndex);
url = (intIndex);
intIndex = (":");
if (intIndex != -1)
{
strTemp = (':');
= strTemp[0];
(strTemp[1], out );
}
intIndex = ("?");
if (intIndex == -1)
{
= url;
}
else
{
strTemp = ('?');
= strTemp[0];
= strTemp[1];
}
}
}
return urlInfo;
}

/// <summary>
/// Make a request and get a response
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="body"></param>
/// <param name="encode"></param>
/// <returns></returns>
private static string GetResponse(string host, int port, string body, Encoding encode)
{
string strResult = ;
byte[] bteSend = (body);
byte[] bteReceive = new byte[1024];
int intLen = 0;

using (Socket socket = new Socket(, , ))
{
try
{
(host, port);
if ()
{
(bteSend, , 0);
while ((intLen = (bteReceive, , 0)) > 0)
{
strResult += (bteReceive, 0, intLen);
}
}
();
}
catch { }
}

return strResult;
}

/// <summary>
/// GET request
/// </summary>
/// <param name="url"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Get(string url, Encoding encode)
{
UrlInfo urlInfo = ParseURL(url);
string strRequest = ("GET {0}?{1} HTTP/1.1\r\nHost:{2}:{3}\r\nConnection:Close\r\n\r\n", , , , ());
return GetResponse(, , strRequest, encode);
}

/// <summary>
/// POST request
/// </summary>
/// <param name="url"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Post(string url, Encoding encode)
{
UrlInfo urlInfo = ParseURL(url);
string strRequest = ("POST {0} HTTP/1.1\r\nHost:{1}:{2}\r\nContent-Length:{3}\r\nContent-Type:application/x-www-form-urlencoded\r\nConnection:Close\r\n\r\n{4}", , , (), , );
return GetResponse(, , strRequest, encode);
}
}
}