c语言udp socket使用案例

int g_udp_sock                                      = -1;
struct sockaddr_in g_udp_server_ip;
uint8_t g_wireshark_enable                          = 1;


static int wireshark_socket_init(const char *dst_ip, uint32_t dst_port)
{
    int ret = 0;
    int option = 1;
    g_udp_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (g_udp_sock < 0) {
        printf("create udp socket error\n");
        return -1;
    }
    setsockopt(g_udp_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option) );

    memset(&g_udp_server_ip, 0, sizeof(g_udp_server_ip));
    g_udp_server_ip.sin_family = AF_INET;
    g_udp_server_ip.sin_addr.s_addr = inet_addr(dst_ip);
    g_udp_server_ip.sin_port = htons(dst_port);
    return 0;
}

int32_t wireshark_socket_init_from_conf()
{
    FILE* fp = fopen("wireshark.conf", "r");
    if (NULL == fp)
        return;
    uint8_t         line[2048]  = {0};
    uint8_t         dip[32]     = {0};
    uint32_t        dport       = 0;
    while(fgets(line, 2048, fp))
    {
        printf("%s\n",line);
        if(line[0] == '#')
            continue;
        sscanf(line, "%s %d", dip, &dport);
        wireshark_socket_init(dip, dport);
    }
    fclose(fp);
    return 0;
}
ssize_t wireshark_packet_send(uint8_t *buff, uint32_t len)
{
    if(g_wireshark_enable == 1){
        return sendto(g_udp_sock,
                      buff,
                      len,
                      0,
                      (struct sockaddr*)(&g_udp_server_ip),
                      sizeof(g_udp_server_ip));
    }
    return 0;
}

 

你可能感兴趣的:(C/C++,socket,udp)