C语言 UDP单播recvfrom

#include 
#include 
#include 
#include  /* superset of previous */
#include 
#include 
#include 
#include 
#include 

int main()
{
    // 1.创建UDP通信对象
    int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);

    // 2.绑定UDP通信socket
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);
    addr.sin_addr.s_addr = INADDR_ANY;

    int ret = bind(udp_socket, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0)
    {
        perror("绑定失败\n");
        return -1;
    }
    else
    {
        printf("绑定成功\n");
    }

    // 3.接收数据
    char buf[1024] = {0};
    printf("等待对方发送数据\n");
    recvfrom(udp_socket, buf, 1024, 0, NULL, NULL);
    printf("接收到数据:%s\n", buf);
   
    // 4.关闭套接字
    close(udp_socket);
}

你可能感兴趣的:(C语言,c语言,udp,开发语言)