我试图让我的双脚与网络编程湿。我创建了一个服务器,它接受来自Web客户端的连接。套接字未能接受客户端?
在某个时刻(我记不清它是什么时候了),并且对于我的生活,我无法得到它的修复。
有人能够给我提供一些指针吗? (没有双关语意)
我已经尝试了所有存在,读取整个网页,包括gnuclibrarydocumentation(我在Linux上),但仍然没有运气。
编辑:问题说明:我的客户端软件管理进行连接,但服务器软件没有这份报告,而且似乎停留在accept()函数得到。
我的代码:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "lib/error.h"
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char *argv[])
{
int socketfd = 0, connfd = 0; // socket, and connection file descriptors
struct sockaddr_in serv_addr; // struct that will get filled with host info
struct sockaddr_in cli_addr; // struct that will get filled with peer info
int status; // Used for various status controling and error messaging throughout the program
char sendBuff[1025]; // buffer to allow for storage of items to be sent
socklen_t cli_size = sizeof(cli_addr);
time_t ticks;
socketfd = socket(AF_INET, SOCK_STREAM, 0); // Creating a socket
if (socketfd == -1) error("Failed to create socket.", 4);
memset(&serv_addr, '0', sizeof(serv_addr)); // zeroing out the location of serv_addr
memset(&cli_addr, '0', sizeof(cli_addr)); // zeroing out the location of serv_addr
memset(sendBuff, '0', sizeof(sendBuff)); // zeroing out the locaiton of sendBuff
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
status = bind(socketfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if (status == -1) error("Failed to bind socket.", 4);
listen(socketfd, 10);
while(1)
{
connfd = accept(socketfd, (struct sockaddr *) &cli_addr, (socklen_t *) &cli_size);
if (connfd == -1) error("Failed during accepting the peer connection at socket.", 3);
printf("Client connected: %d:%d", cli_addr.sin_addr.s_addr, cli_addr.sin_port);
close(connfd);
sleep(1);
}
return 0;
}
我不知道这是否完全相关,但是你的memset没有清零内存 - 它将它设置为字符“0”的ASCII值,这是非常不同的。 –
@ChrisHayes真的吗?这不是我第一次看到这个,但从来没有真正研究过它,我认为它正在清理记忆。但我必须指出,这个'0'让我陷入了思考。 – NlightNFotis
你可以在'printf'之后调用'fflush(stdout)'吗? – cnicutar