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++ ヘッダーは、多くの場合、移植性のために型を定義し、特定の関係を強制します。

これまで見てきたように、多くのコードが警告付きでコンパイルおよび実行されます。

ただし、これらは理由による警告です。

そうしないと、ある日、サイズと署名が重要な特殊なケースに陥る可能性があり、それが機能しない理由がわからないでしょう。常に、使用しているライブラリの規則に従うようにしてください。

現在の警告を修正するには、socksizeとして宣言する必要がありますsocklen_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 に答える