C:listen()API返回-1

时间:2015-08-17 16:41:25

标签: c windows sockets

我正在使用下面的代码在c中创建服务器程序。代码取自here

#include <Winsock.h>
#include <string.h>
#include <ws2tcpip.h>
#include<conio.h>

int main(){
  int welcomeSocket, newSocket;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size;

  /*---- Create the socket. The three arguments are: ----*/
  /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);

  /*---- Configure settings of the server address struct ----*/
  /* Address family = Internet */
  serverAddr.sin_family = AF_INET;
  /* Set port number, using htons function to use proper byte order */
  serverAddr.sin_port = htons(7891);
  /* Set IP address to localhost */
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  /* Set all bits of the padding field to 0 */
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*---- Bind the address struct to the socket ----*/
  bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

  /*---- Listen on the socket, with 5 max connection requests queued ----*/
  if(listen(welcomeSocket,5)==0)
    printf("Listening\n");
  else
    printf("Error %d\n",listen(welcomeSocket,5));

  /*---- Accept call creates a new socket for the incoming connection ----*/
  addr_size = sizeof serverStorage;
  newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);

  /*---- Send message to the socket of the incoming connection ----*/
  strcpy(buffer,"Hello World\n");
  send(newSocket,buffer,13,0);
  getch();
  return 0;
}

我已经稍微更改了代码以使其在dev-c中工作,但在输出中它是打印错误,即它正在执行else条件。任何人都知道为什么?以及如何调试这个?

我已经尝试更改端口号。它不起作用。

1 个答案:

答案 0 :(得分:5)

在Windows上,您必须首先通过调用WSAStartup初始化网络子系统,然后才能对套接字/网络相关功能进行任何调用。

WSADATA wsaData;
int wsaRc = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (wsaRc != 0) {
   fprintf(stderr, "WSAStartup failed with error: %d\n", wsaRc);
   return 1;
}

/* Socket related functions callable from here on */

您链接的示例代码是为UNIX系统编写的,它没有API要求。

请注意,您也是

  

[...]必须为每次成功调用WSACleanup函数   调用WSAStartup函数的时间。

(来自WSAStartup文档)。