基于UDP套接字编程实例

data.h

 #ifndef DATA_H
#define DATA_H
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#define PORT 4578
#define maxn 100 #endif

server.c

 #include "data.h"
int main()
{
int sockfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t len;
int num;
char buf[maxn];
if((sockfd = socket(AF_INET,SOCK_DGRAM,)) == -)
{
fprintf(stderr,"socket fail,error:%s\n",strerror(errno));
return -;
}
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr*)&server,sizeof(server)) == -)
{
fprintf(stderr,"bind fail,error:%s\n",strerror(errno));
return -;
}
len = sizeof(client);
bzero(&buf,sizeof(buf));
while()
{
num = recvfrom(sockfd,buf,maxn,,(struct sockaddr*)&client,&len);
if(num < )
{
perror("recvfrom() error!\n");
exit();
}
num--;
buf[num] = '\0';
printf("You got a message <%s> from client.\n",buf);
printf("It is ip is %s,port is %d.\n",
inet_ntoa(client.sin_addr), htons(client.sin_port));
sendto(sockfd,buf,strlen(buf),,(struct sockaddr*)&client,len);
if(!strcmp(buf,"bye"))
break;
}
close(sockfd); }

client.c

#include "data.h"
int main()
{
int sockfd,num;
char sendbuf[maxn];
char recvbuf[maxn];
struct sockaddr_in server;
struct sockaddr_in peer;
if((sockfd = socket(AF_INET,SOCK_DGRAM,)) == -)
{
fprintf(stderr,"socket fail,error %s\n",strerror(errno));
exit();
}
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
bzero(&sendbuf,sizeof(sendbuf));
bzero(&recvbuf,sizeof(recvbuf));
while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL)
{
int tt = strlen(sendbuf);
sendto(sockfd,sendbuf,tt,,(struct sockaddr*)&server,sizeof(server));
socklen_t len;
recvfrom(sockfd,recvbuf,maxn,,NULL,NULL);
printf("receive message is :");
fputs(recvbuf,stdout);
printf("\n");
bzero(&sendbuf,sizeof(sendbuf));
bzero(&recvbuf,sizeof(recvbuf));
}
close(sockfd);
return ;
}

运行结果:

基于UDP套接字编程实例

上一篇:深入理解Java虚拟机(类文件结构+类加载机制+字节码执行引擎)


下一篇:C++ 基类指针,子类指针,多态