gpt4 book ai didi

c - C 错误中的套接字

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:55 24 4
gpt4 key购买 nike

我是第一次使用 C 套接字,我的代码遇到了一个小错误。当我编译它工作正常并且编译良好时它只是抛出一些错误,我想知道如何修复它们。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORTNUM 2343

int main(int argc, char *argv[])
{
char msg[] = "Hello World !\n";

struct sockaddr_in dest; /* socket info about the machine connecting to us */
struct sockaddr_in serv; /* socket info about our server */
int mysocket; /* socket used to listen for incoming connections */
int socksize = sizeof(struct sockaddr_in);

memset(&serv, 0, sizeof(serv)); /* zero the struct before filling the fields */
serv.sin_family = AF_INET; /* set the type of connection to TCP/IP */
serv.sin_addr.s_addr = INADDR_ANY; /* set our address to any interface */
serv.sin_port = htons(PORTNUM); /* set the server port number */

mysocket = socket(AF_INET, SOCK_STREAM, 0);

/* bind serv information to mysocket */
bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr));

/* start listening, allowing a queue of up to 1 pending connection */
listen(mysocket, 1);
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);

while(consocket)
{
printf("Incoming connection from %s - sending welcome\n", inet_ntoa(dest.sin_addr));
send(consocket, msg, strlen(msg), 0);
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
}

close(consocket);
close(mysocket);
return EXIT_SUCCESS;
}

我从一个网站上得到这个作为一个简单的例子。

这是编译错误:

server.c: In function ‘main’:
server.c:33:46: warning: pointer targets in passing argument 3 of ‘accept’ differ in signedness [-Wpointer-sign]
/usr/include/i386-linux-gnu/sys/socket.h:214:12: note: expected ‘socklen_t * __restrict__’ but argument is of type ‘int *’
server.c:39:46: warning: pointer targets in passing argument 3 of ‘accept’ differ in signedness [-Wpointer-sign]
/usr/include/i386-linux-gnu/sys/socket.h:214:12: note: expected ‘socklen_t * __restrict__’ but argument is of type ‘int *’

感谢您的帮助! :)

最佳答案

C 和 C++ header 通常定义类型以实现可移植性和强制执行某些关系。

如您所见,很多代码在编译和运行时都会出现警告。

但是,它们是警告是有原因的。

否则,有一天您可能会遇到大小和符号很重要的极端情况,而您将不知道为什么它不起作用。始终尝试遵循您正在使用的库的约定。

要修复当前的警告,您需要将 socksize 声明为 socklen_t

关于c - C 错误中的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com