学逆向论坛

找回密码
立即注册

只需一步,快速开始

发新帖

2万

积分

41

好友

1168

主题
发表于 2020-6-15 20:55:43 | 查看: 5221| 回复: 0
第一版
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

#define BUF_SIZE 2048
#define BUF_SMALL 100

void Send_404(SOCKET sock)
{
char Protocol[] = "HTTP/1.0 404 Bad Request\r\n";
send(sock, Protocol, strlen(Protocol),0);
closesocket(sock);
}

void SendData(SOCKET sock, char *filename)
{
char Protocol[] = "HTTP/1.1 200 OK\r\n";
char ServerType[] = "Server:MyWebServer\r\n";
char ContentLen[] = "Content-length:2048\r\n";
char ContentType[] = "Content-type:text/html\r\n";
char buffer[BUF_SIZE] = {0};
FILE *fp;
if ((fp = fopen(filename, "r")) != NULL)
{
// 传输头数据
send(sock, Protocol, strlen(Protocol), 0);
send(sock, ServerType, strlen(ServerType), 0);
send(sock, ContentLen, strlen(ContentLen), 0);
send(sock, ContentType, strlen(ContentType), 0);

// 传输数据
while (fgets(buffer, BUF_SIZE, fp) != NULL)
send(sock, buffer, strlen(buffer), 0);
closesocket(sock);
}
}

unsigned WINAPI RequestHandle(void *argv)
{
SOCKET hClntSock = (SOCKET)argv;

char Buffer[BUF_SIZE] = { 0 };
char Method[BUF_SMALL] = { 0 };
char FileName[BUF_SMALL] = { 0 };

recv(hClntSock, Buffer, BUF_SIZE, 0);

// 寻找HTTP请求头 如果不为空则继续
if (strstr(Buffer, "HTTP/1") != NULL)
{
// 接着判断是否为GET请求方式
strcpy(Method, strtok(Buffer, "/"));
if (strcmp(Method, "GET") != 0)
{
strcpy(FileName, strtok(0, "/"));
printf("请求方式: %s 请求文件: %s \n", Method,FileName);
SendData(hClntSock, FileName);
closesocket(hClntSock);
return 0;
}
}

Send_404(hClntSock);
closesocket(hClntSock);
return -1;
}

int main(int argc,char * argv[])
{
WSADATA wsaData;
SOCKET ServerSock, ClientSock;
SOCKADDR_IN ServerAddr, ClientAddr;

WSAStartup(MAKEWORD(2, 2), &wsaData);
ServerSock = socket(PF_INET, SOCK_STREAM, 0);
memset(&ServerAddr, 0, sizeof(ServerAddr));

ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
ServerAddr.sin_port = htons(80);

bind(ServerSock, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr));
listen(ServerSock, 10);

while (1)
{
HANDLE hThread;
DWORD dwThreadID;
int ClientAddrSize;

ClientAddrSize = sizeof(ClientAddr);
ClientSock = accept(ServerSock, (SOCKADDR *)&ClientAddr, &ClientAddrSize);

printf("请求客户端 IP: %s --> 端口: %d \n", inet_ntoa(ClientAddr.sin_addr), ntohs(ClientAddr.sin_port));
hThread = (HANDLE)_beginthreadex(0, 0, RequestHandle, (void *)ClientSock, 0, (unsigned *)&dwThreadID);
}
closesocket(ServerSock);
WSACleanup();
return 0;
}


温馨提示:
1.如果您喜欢这篇帖子,请给作者点赞评分,点赞会增加帖子的热度,评分会给作者加学币。(评分不会扣掉您的积分,系统每天都会重置您的评分额度)。
2.回复帖子不仅是对作者的认可,还可以获得学币奖励,请尊重他人的劳动成果,拒绝做伸手党!
3.发广告、灌水回复等违规行为一经发现直接禁言,如果本帖内容涉嫌违规,请点击论坛底部的举报反馈按钮,也可以在【投诉建议】板块发帖举报。
论坛交流群:672619046

小黑屋|手机版|站务邮箱|学逆向论坛 ( 粤ICP备2021023307号 )|网站地图

GMT+8, 2024-11-21 19:34 , Processed in 0.142446 second(s), 39 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表