我正在尝试通过制作一个非常简单的http网络服务器来学习C语言中的winsock。目前我可以提供单个网页。我想基于浏览器中的url实现一个文件系统。如何获取客户端请求的URL?
// socketprogramming4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <dos.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
bool send_all(int socket, void *buffer, size_t length)
{
char *ptr = (char*)buffer;
while (length > 0)
{
int i = send(socket, ptr, length, 0);
if (i < 1) return false;
ptr += i;
length -= i;
}
shutdown(socket, 1);
return true;
}
int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c;
char *message, server_reply[2000];
int recv_size;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(80);
//Bind
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
//Listen to incoming connections
listen(s, 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
message = "<!DOCTYPE html><html><head><link rel='stylesheet' href='index.css' /></head><body>Testing</body></html>";
send_all(new_socket, message, strlen(message));
}
if (new_socket == INVALID_SOCKET)
{
printf("accept failed with error code : %d", WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}