udp实现客户端服务器

服务器端:

#include
#include
#include
#include
#include
#include
#include
#include//服务器端

int main()
{
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);//数据报服务的套接子
    assert( sockfd!=-1);

    struct sockaddr_in saddr;
    memset(&saddr,0,sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6000);//端口,网络字节序列,大端
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
    assert(res != -1);

    while(1)
    {
        struct sockaddr_in caddr;
        int len = sizeof(caddr);
        char buff[128] = {0};

        int n=recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr,&len);
        printf("recv(%d):%s\n",n,buff);

        sendto(sockfd,"ok",2,0,(struct sockaddr*)&caddr,sizeof(caddr));
    }

}

客户端:

#include
#include
#include
#include
#include
#include
#include
#include//客户端

int main()
{
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);//数据包服务的套接子
    assert( sockfd!=-1);

    struct sockaddr_in saddr;//代表服务器的端口:ip port
    memset(&saddr,0,sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6000);//指定服务器的端口
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");//指定服务器的ip


    while(1)
    {
        char buff[128]={0};

        printf("input:\n");

        fgets(buff,128,stdin);

        if(strncmp(buff,"end",3)==0)
        break;

        sendto(sockfd,buff,strlen(buff),0,(struct sockaddr*)&saddr,sizeof(saddr));
        memset(buff,0,128);
        int len =sizeof(saddr);
        recvfrom(sockfd,buff,127,0,(struct sockaddr*)&saddr,&len);
        printf("buff=%s\n",buff);

    }

    close(sockfd);
}

你可能感兴趣的:(Linux,udp,服务器,linux)