我正在尝试编写一个程序,它接收端口号作为命令行参数并启动HTTP服务器。我正在通过listenfd来接受()来做这件事。但是,我从open_listenfd()获得了权限,然后从Accept()获得了错误的描述符错误。
从中复制open_listenfd()和Accept()函数 http://csapp.cs.cmu.edu/2e/ics2/code/src/csapp.c
我将端口100传递给程序:
int open_listenfd(int port)
{
int listenfd, optval=1;
struct sockaddr_in serveraddr;
/* Create a socket descriptor */
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
return -1;
/* Eliminates "Address already in use" error from bind */
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)) < 0)
return -1;
/* Listenfd will be an endpoint for all requests to port on any IP address for this host */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
/* Make it a listening socket
* ready to accept connection
* requests */
if (listen(listenfd, LISTENQ) < 0)
return -1;
return listenfd;
}
int Open_listenfd(int port)
{
int rc;
if ((rc = open_listenfd(port)) < 0)
unix_error("Open_listenfd error");
return rc;
}
int Accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
int rc;
if ((rc = accept(s, addr, addrlen)) < 0)
unix_error("Accept error");
return rc;
}
int main(int argc, char **argv) {
int listenfd, connfd, port, clientlen;
struct sockaddr_in clientaddr;
struct hostent *phost;
char *phostaddr;
port = atoi(argv[1]);
listenfd = Open_listenfd(port);
clientlen = sizeof(clientaddr);
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
printf("%d\n", connfd);
printf("%s\n", strerror(errno));
return 0;
}
另一个问题是,如果我想让服务器不断地接受()连接,请读取表单
的请求GET /path HTTP/1.1\r\n\r\n
我该怎么做?
答案 0 :(得分:6)
1024以下的端口被认为在Linux中具有特权,因此您需要成为root用户才能在端口上打开套接字&lt; 1024