UDP服务器以及客户端

1.服务器

#include 
#include 
#include 
#include 
#include 

#define BUF_SIZE          (1024)
#define UDP_SERVER_PORT   (8101)
#define UDP_SERVER_ADDR  "192.168.7.33"
#define ERROR_LOG(msg) \
                  do {            \
                          fprintf(stderr, msg); \
                          exit(1);     \
                     } while (0)

int main (VOID)
{
    struct sockaddr_in  serveraddr;
    socklen_t           socklen = sizeof(serveraddr);
    char                localbuf[BUF_SIZE] = {0};
    int                 sockfd;
    int                 ret;
    ssize_t                 getret;


    bzero(&serveraddr, socklen);
    printf("UDP Server Start!!!\n");
    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd < 0) {
        ERROR_LOG("socket failed\n");
    }

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(UDP_SERVER_PORT);
    serveraddr.sin_addr.s_addr =inet_addr((UDP_SERVER_ADDR));


    ret = bind(sockfd, (struct sockaddr *)&serveraddr, socklen);
    if (ret < 0) {
        ERROR_LOG("bind error\n");
    }

//    bzero(localbuf, sizeof(localbuf));
    printf("Ready to recv data#############\n");

    while(1){

        getret = recvfrom(sockfd, localbuf, BUF_SIZE, 0, (struct sockaddr *)&serveraddr, &socklen);

        if (getret <= 0) {
            ERROR_LOG("recvfrom failed\n");
        } else {
            printf("recvfrom  data successful!!!\n");
            printf("recv data:%s\n", localbuf);
        }

    }

    close(sockfd);

    return  (0);
}

2.客户端

/*
 * udp_client.c
 *
 *  Created on: Aug 16, 2018
 *      Author: zhangyazhong
 */


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUF_SIZE          (1024)
#define UDP_SERVER_PORT   (8101)
#define UDP_SERVER_ADDR   "192.168.7.33"
#define ERROR_LOG(msg) \
                  do {            \
                          fprintf(stderr, msg); \
                          exit(1);     \
                     } while (0)

int main(VOID)
{
    int iSock, iRet;
    char  pSendBuf[BUF_SIZE] = "The Data from client!";
    struct sockaddr_in serverAddr;
    socklen_t addrLen = sizeof(serverAddr);

    printf("UDP Client Start!!!!!\n");
    iSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(iSock < 0){
        ERROR_LOG("socket error\n");
    }

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(UDP_SERVER_ADDR);
    serverAddr.sin_port = htons(UDP_SERVER_PORT);

    printf("send data is %s\n", pSendBuf);

    while(1){
        iRet = sendto(iSock, pSendBuf, BUF_SIZE, 0, (struct sockaddr *)&serverAddr, addrLen);
        if(iRet < 0){
            ERROR_LOG("Send message failed\n");
        }else{
            printf("Send Success!\n");
        }
        sleep(2);
    }


}

 

你可能感兴趣的:(c,网络,UDP)