2

我第一次使用 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 *’

谢谢您的帮助!:)

4

2 回答 2

6

C 和 C++ 头文件通常为可​​移植性和强制某些关系定义类型。

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

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

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

要修复当前的警告,您需要声明socksizesocklen_t.

于 2012-11-05T22:45:04.920 回答
2
int socksize = sizeof(struct sockaddr_in);

=>

socklen_t           nAddrLen;
nAddrLen = sizeof(struct sockaddr_in);
于 2012-11-06T00:53:52.050 回答