/*
server
编译命令: gcc -Wall -g -o server -lpthread
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 8458
void udp_recv(int fd)
{
char strRecv[1024] = {"\0"};
int iRecvLen = -1,iSize;
struct sockaddr_in cli;
iSize = sizeof(cli);
while(1)
{
memset(strRecv,0x00,sizeof(strRecv));
iRecvLen = recvfrom(fd,strRecv,sizeof(strRecv),0,(struct sockaddr *)&cli,&iSize);
//strRecv[iRecvLen] = '\0';
if (strlen(strRecv) > 0)
{
printf("RecvLen:%d,context:%s\n",iRecvLen,strRecv);
}
}
return ;
}
int main()
{
struct sockaddr_in SerAddr;
int serfd = -1,iSize = -1;
iSize = sizeof(SerAddr);
serfd = socket(PF_INET,SOCK_DGRAM,0);
if (0 > serfd)
{
printf("init socket failed:%d\n",serfd);
return 0;
}
memset(&(SerAddr),0x00,sizeof(struct sockaddr_in));
SerAddr.sin_family = AF_INET;
SerAddr.sin_port = htons(PORT);
SerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ( 0 > bind(serfd,(struct sockaddr *)&SerAddr,iSize))
{
printf("server bind to port %d failed \n",PORT);
return 0;
}
udp_recv(serfd);
return 0;
}
/*
client
编译命令: gcc -Wall -g -o client -lpthread
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
void udp_send(int udpfd)
{
int i = 0,iSerPort = 8458,iSize = 0;;
char buf[128] = {"\0"},sIP[64] = {"127.0.0.1"};
int iLen = 128;
struct sockaddr_in peer;
iSize = sizeof(peer);
for (i = 0; i < 10; i++)
{
bzero((char *)&peer,sizeof(struct sockaddr_in));
peer.sin_family = AF_INET;
peer.sin_port = htons(iSerPort);
peer.sin_addr.s_addr = inet_addr(sIP);
memset(buf,0x00,sizeof(buf));
sprintf(buf,"string%d-string%d-string%d-string%d-string%d",i + 1,i + 1,i + 1,i + 1,i + 1);
printf("send message:%s\n",buf);
iLen = sendto(udpfd,buf,strlen(buf) + 1,0,(struct sockaddr *)&peer,iSize);
if ( 0 > iLen)
{
printf("send failed\n");
}
}
return;
}
int main()
{
struct sockaddr_in SerAddr;
int udpfd = -1,iPort = 8456;
udpfd = socket(AF_INET,SOCK_DGRAM,0);
if(udpfd < 0)
{
printf("socket error:%s\n",strerror(errno));
return -1;
}
memset(&(SerAddr),0x00,sizeof(SerAddr));
SerAddr.sin_family = AF_INET;
SerAddr.sin_port = htons(iPort);
SerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ( 0 > bind(udpfd,(struct sockaddr *)&SerAddr,sizeof(struct sockaddr)) )
{
printf("bind failed:%s\n",strerror(errno));
return -1;
}
udp_send(udpfd);
printf("\nclient exit!\n\n");
return 0;
}