基于UDP的通信时不可靠地,面向无连接的,发送的数据无法确切知道对方收到没有,通常用于对可靠性要求不高的通信中,使用简单,UDP没有严格区分server端和client端,唯一的区别是绑不绑定(bind)端口。

1,接收程序(server)

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#define SERV_PORT 27350

int main(int argc, char **argv)
{

 
    int sock_fd;
    char rcv_buff[512];
    struct sockaddr_in client_addr;
    struct sockaddr_in server_addr;
    int client_len;
    int rcv_num = -1;

    if ((sock_fd = socket(AF_INET, SOCK_DGRAM,0)) < 0)
    {
        perror("socket create error\n");
        exit(1);
    }

    memset(&server_addr,0,sizeof(struct sockaddr_in));
    
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERV_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    client_len = sizeof(struct sockaddr_in);

    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0)
    {
        perror("bind error.\n");
        exit(1);
    }
    
    while (1)
    {
        rcv_num= recvfrom(sock_fd, rcv_buff, sizeof(rcv_buff), 0, (struct sockaddr*)&client_addr, &client_len);
        if (rcv_num>0)
        {
            rcv_buff[rcv_num] = '\0';
            printf("%s %u says: %s\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port),rcv_buff);
            
        }
        else
        {
            perror("recv error\n");
            break;
        }
    }
    close(sock_fd);
    return 0;
}

2,发送程序(client)

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>


int main(void)
{
    int sock_send_fd;
    struct sockaddr_in addr;
    char buff[20];
    memset(&addr,0,sizeof(struct sockaddr_in));
    
    if ((sock_send_fd = socket(AF_INET, SOCK_DGRAM,0)) < 0)
        {
            perror("socket create error\n");
            exit(1);
        }

        addr.sin_family = AF_INET;
        addr.sin_port = htons(27350);
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        if (addr.sin_addr.s_addr == INADDR_NONE)
        {
            printf("Incorrect ip address!\n");
            close(sock_send_fd);
            exit(1);
        }
    
    sprintf(buff,"%d,%d,%d,%d,%d",1,2,3,4,5);
    while (1)
    {
        int n;
        n = sendto(sock_send_fd , buff, strlen(buff), 0, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            perror("sendto");
            close(sock_send_fd);
            break;
        }
    
    return 0;
}
}