【发布时间】:2025-03-01 13:20:02
【问题描述】:
我正在尝试创建一个 tcpServer 和 tcpClient 消息终端。我遇到了一些我无法工作的代码问题
我在这里关注本指南https://www.youtube.com/watch?v=BIJGSQEipEE
int newSocket = accept(sockfd, (struct sockaddr*)&newAddr, sizeof(newAddr));
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntoa(newAddr.sin_port));
我的错误代码是:
tcpServer.c:50:64: warning: incompatible integer to pointer conversion passing 'unsigned long' to parameter of type 'socklen_t *' (aka 'unsigned int *') [-Wint-conversion]
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, sizeof(newAddr));
^~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/sys/socket.h:686:73: note: passing argument to parameter here
int accept(int, struct sockaddr * __restrict, socklen_t * __restrict)
^
tcpServer.c:54:81: warning: implicit declaration of function 'ntoa' is invalid in C99 [-Wimplicit-function-declaration]
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntoa(newAddr.sin_port));
为什么会出现错误2?
谢谢你帮助我:)
【问题讨论】:
-
POSIX
accept()的第三个参数必须是“指向socklen_t的指针”。您的代码试图传递不兼容的size_t类型的值。显然,您链接到的 youtube 指南包含错误信息