导航

linux UDP的简单例子

Posted on 2012-04-09 16:06  网名还没想好  阅读(500)  评论(0编辑  收藏  举报

服务器端:

    #include<stdio.h>
    #include<stdlib.h>
    #include<sys/socket.h>
    #include<arpa/inet.h>
    #include<string.h>
    #include<errno.h>
    #include<unistd.h>
    #define BUFSIZE 1024
    int main(void)
    {
            struct sockaddr_in local_addr,remote_addr;
            int sockfd;
            int server_ip,nrecv;
            int alen;
            FILE *fp;
            char buffer[BUFSIZE];

            memset(&local_addr,0,sizeof(local_addr));
            local_addr.sin_family=AF_INET;
            local_addr.sin_port=htons(5666);

          inet_pton(AF_INET,"127.0.0.1",(void*)&server_ip);
          local_addr.sin_addr.s_addr=server_ip;

            sockfd=socket(AF_INET,SOCK_DGRAM,0);
            if(bind(sockfd,(struct sockaddr*)&local_addr,sizeof(struct sockaddr))<0){
                    fprintf(stderr,"error:bind() error!\n");
                    exit(-1);
            }

            printf("====================Begin to service====================\n");
            while(1){
                    if((nrecv=recvfrom(sockfd,buffer,BUFSIZE,0,(struct sockaddr*)&remote_addr,&alen))<0){
                            fprintf(stderr,"error:%s\n",strerror(errno));
                            exit(1);
                    }else
                    {
                        buffer[nrecv]='\0';
                        sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr*)&remote_addr,alen);
                    }
            }
            exit(0);
    }
客户端:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 1234
#define MAXDATASIZE 100

int main(int argc, char *argv[])
{
int fd, numbytes;
int server_ip;
char recvbuf[MAXDATASIZE];
char sendbuf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server,client;
if ((fd=socket(AF_INET, SOCK_DGRAM, 0))==-1){
printf("socket() error\n");
exit(1);
}

bzero(&server,sizeof(server));
server.sin_family=AF_INET;
      server.sin_port=htons(5666);
            inet_pton(AF_INET,"127.0.0.1",(void*)&server_ip);
            server.sin_addr.s_addr=server_ip;

        socklen_t len;
         len=sizeof(struct sockaddr_in);
while (1) {
   printf("input message:");
         fgets(sendbuf,40,stdin);
sendto(fd,sendbuf,strlen(sendbuf),0,(struct sockaddr *)&server,len);
if ((numbytes=recvfrom(fd,recvbuf,MAXDATASIZE,0,(struct sockaddr *)&server,&len)) == -1){
printf("recvfrom() error\n");
exit(1);
}
recvbuf[numbytes]='\0';
printf("Server Return Reverse Message: %s\n",recvbuf);

}

close(fd);
}
完毕