1. 程式人生 > >C程式設計之基於UDP的網路通訊

C程式設計之基於UDP的網路通訊

/*
* udp-c.c
* Author: Alvin
* 基於UDP的客戶端程式碼
* 功能:向伺服器傳送內容,並接收來自服務端的回覆
*
*/



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

#define MYPORT 6768
#define BUFSIZE 20

int main(int
 argc, char *argv[])
{
    if (argc != 3)
    {
        printf("\nUsing: ./udp-c IP string\n");
        printf("\tThe length of the string should not bigger than 20.\n\n");
        exit(0);
    }

     int sockfd;
         int new_fd,numbytes,ret;
         struct sockaddr_in udp_addr;
         struct sockaddr_in
 their_addr;
         int their_addr_len=sizeof(their_addr);
         int sin_size,con_fd,pid;
         int buflen;
         char recive[BUFSIZE];

        sockfd=socket(AF_INET,SOCK_DGRAM,0);
         if(sockfd<0)
         {
            printf("error in socket");
            exit(1);
        }

         udp_addr.
sin_family=AF_INET;
        udp_addr.sin_port=htons(MYPORT);
        udp_addr.sin_addr.s_addr=inet_addr(argv[1]);
         buflen=strlen(argv[2]);
         while(1)
         {
                   ret = sendto(sockfd,argv[2],buflen,0,(struct sockaddr*)&udp_addr,sizeof(udp_addr));
                   if(ret<0)
                   {
                            printf("error recive\n");
                            exit(1);
                   }
                   printf("UDP client sent:%s\n",argv[2]);
                   sleep(1);

                   ret = recvfrom(sockfd,recive,BUFSIZE,0,(struct sockaddr*)&their_addr,&their_addr_len);
                   if(ret<0)
                   {
                            printf("error recive\n");
                            exit(1);
                   }
                   recive[ret]='\0';

                   printf("UDP client recive:%s\n",recive);
 
        }

       return 0;
}