简体   繁体   English

C (UDP) 中的套接字服务器不接收数据包。 怎么做?

[英]Socket server in C (UDP) doesn't receive packets. How to do?

I've done a UDP socket server in C. The server works properly only if the packets are send to 127.0.0.1.我已经在 C 中完成了一个 UDP 套接字服务器。只有当数据包被发送到 127.0.0.1 时,服务器才能正常工作。 I'm trying to test it with packet sender, and I want to open a socket at the address 192.168.231.54.我正在尝试使用数据包发送方对其进行测试,并且我想在地址 192.168.231.54 处打开一个套接字。 Anyway, if I write this address in the code, I receive an error ("Cannot assign requested address"), and this error appears for each single address different from 127.0.0.1.无论如何,如果我在代码中写入这个地址,我会收到一个错误(“无法分配请求的地址”),并且对于每个与 ​​127.0.0.1 不同的地址都会出现此错误。 I want to open a socket to 192.168.231.54 and I want to send packets to this address with Packet Sender.我想打开一个到 192.168.231.54 的套接字,我想用 Packet Sender 将数据包发送到这个地址。

Here is the server code:这是服务器代码:

//*********SOCKET OPENING**************
   
    int fd;
    struct sockaddr_in serveraddr, cliaddr;

    if ( (fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
        perror( "socket failed" );
        exit(EXIT_FAILURE);
    }
        
    memset( &serveraddr, 0, sizeof(serveraddr) );
    memset(&cliaddr, 0, sizeof(cliaddr));

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(50037);
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);  

    if ( bind(fd, (const struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0 ) {
        perror( "bind failed" );
        exit(EXIT_FAILURE);
    }
    else{
        perror("socket opened");
    }

    //Receiving data into hex_array array
    char hex_array[lenght];
    int len;
    len = sizeof(cliaddr);
    int n = recvfrom(fd, (uint8_t *)hex_array, lenght, NULL, ( struct sockaddr *) &cliaddr, &len);
    //Printing of the received data on the socket
    printf("START DEBUG:\n");
    printf("%s\n", hex_array);
    printf("END DEBUG.\n");

The address you bind the socket to has to actually be your computer's IP address.您绑定套接字的地址必须实际上是您计算机的 IP 地址。 You can't just pick a random address.你不能随便选择一个地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM