C: listen() API 返回 -1

标签 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 条件。任何人都知道为什么?以及如何调试它?

我试过更改端口号。它没有用。

最佳答案

在 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 要求。


请注意,您还

[...] must call the WSACleanup function for every successful time the WSAStartup function is called.

(来自 WSAStartup 文档)。

关于C: listen() API 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055573/

相关文章:

windows - 批处理文件暂停需要两次按键才能关闭

c++ - 通过HttpOpenRequestA发送POST数据

android - 关闭 Activity 时如何停止 Activity 的线程和套接字

c# - 以编程方式卸载掌上电脑程序

c - 返回的字符串值变成垃圾

c - 如何处理二进制数据中的 Windows/Unix EOF 警告?

c++ - 如何用 C++ 编写一段代码来查找系统路径上文件的完整路径?

c - 在 C 语言中使用 HTTP 从嵌入式系统传输文件

c - gets 和 mmap 的问题

C 中的 char 指针和 strcpy