Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C错误中的套接字_C_Sockets_Networking - Fatal编程技术网

C错误中的套接字

C错误中的套接字,c,sockets,networking,C,Sockets,Networking,我第一次使用C套接字,我的代码遇到了一个小错误。当我编译时,它工作正常,编译良好,只会抛出一些错误,我想知道如何修复它们 代码如下: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/i

我第一次使用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;
}

谢谢你的帮助!:)

> P> C和C++头通常定义可移植性的类型和执行某些关系。 正如您所看到的,许多代码在编译和运行时都会出现警告

然而,这些警告是有原因的

否则,有一天,你可能会陷入一个角落,大小和标志性都很重要,你不知道为什么它不起作用。始终尝试遵循您正在使用的库的约定

要修复当前警告,您需要将
socksize
声明为
socklen\u t

int socksize = sizeof(struct sockaddr_in);
=>


这些只是警告,不是错误。但是,最好将
socksize
声明为
socklen\u t
。API希望您使用
socklen\u t*
,但是您将
int*
传递给@user1626342,不需要将一行更改为两行。实际上,初始化也不是,因为这是accept()的输出参数,而不是输入。
socklen_t           nAddrLen;
nAddrLen = sizeof(struct sockaddr_in);