我在 C 中有以下服务器代码。Web 浏览器将用作客户端。到目前为止,我所知道的是我需要从终端运行可执行文件并打开网络浏览器并输入:localhost:54321
. 54321 是我们需要运行 Web 服务器的端口号。接下来我们需要做的是解析从 Web 浏览器接收到的 http 请求,并获取所请求对象的名称。
我知道如何解析但是I don't know how to receive the object
. 我应该使用form
输入来获取对象的名称吗?
提前致谢!只是套接字编程的新手,我只能创建套接字。
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int listenfd,connfd;
struct sockaddr_in servaddr,cliaddr;
socklen_t len = sizeof(cliaddr);
char cli_ip[32];
char mesg[1024];
listenfd = socket(PF_INET,SOCK_STREAM,0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(54321);
if ( bind( listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr) ) < 0 ){
perror(NULL);
exit(-1);
}
//not present in udp server
listen(listenfd,2);
while(1){
//not present in udp server
connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&len);
inet_ntop(AF_INET,(struct in_addr *) &cliaddr.sin_addr, cli_ip, sizeof(cli_ip) );
printf("Client %s connected. \n",cli_ip);
while(1){
memset(mesg,0,sizeof(mesg));
if( recvfrom(connfd,mesg,sizeof(mesg),0,(const struct sockaddr *)&cliaddr,&len) > 0 ){
printf("From %s port %d: %s",cli_ip,ntohs(cliaddr.sin_port),mesg);
}
else {
printf("Client %s disconnected. \n",cli_ip);
break;
}
}
close(connfd);
}
close(listenfd);
return 0;
}
编辑:这是给出的确切规格:
Parse the HTTP request (using strtok) received from the web browser and obtain the name of the object requested. For example, index.html will be sent in the response:
GET /index.html HTML/1.1
Host: localhost:54321
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8