/******************************************************************************
********************************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include
#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100
int main(int argc, char *argv[])
{
int sd,rc,n,cliLen;
struct sockaddr_in cliAddr,servAddr;
char msg[MAX_MSG];
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0)
{
printf("%s:cannot open socket \n",argv[0]);
exit(1);
}
serAddr.sin_family = AF_INET;
serAddr.sin_addr.s_addr=htonl(INADDR_ANY);
serAddr.sin_port =htons(LOCAL_SERVER_PORT);
rc = bind(sd,(struct sockaddr *) &serAddr,sizeof(serAddr));
if(rc<0)
{
printf("%s:cannot bind port number %d\n",argv[0],LOCAL_SERVER_PORT);
exit(1);
}
printf("%s:waiting for data on port UDP%u\n",argv[0],LOCAL_SERVER_PORT);
while(1)
{
memset(nsg,0x0,MAX_MSG);
cliLen=sizeof(cliAddr);
/*******receiving message*********/
n=recvfrom(sd,msg,MAX_MSG,0,(struct sockaddr *)&cliAddr,&cliLen);
if(n<0)
{
printf("%s:cannot receive data\n",argv[0]);
continue;
}
/*******print the received message*********/
printf("%s:from %s:UDP%u:%s\n",argv[0],inet_ntoa(cliAddr.sin_addr),ntohs(cliAddr.sin_port),msg);
}
}
/************Client******************/
/******************************************************************************
********************************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100
int main(int argc, char *argv[])
{
int sd,rc,i;
struct sockaddr_in cli_Addr,remote_Serv_Addr;
struct hostent *h;
if(argc<3)
{
printf("usage : %s....\n",argv[0]);
exit(1);
}
h=gethostbyname(argv[1]);
if(h==NULL)
{
printf("%s: unknown host '%s'\n",argv[0],argv[1]);
exit(1);
}
printf("%s:sending data to '%s'(ip:%s)\n",argv[0],h->h_name,inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));
remote_Serv_Addr.sin_family =h->h_addrtype;
memcpy((char *)&remote_Serv_Addr.sin_addr.s_addr,h->h_addr_list[0],h->h_length);
remote_Serv_Addr.sin_port=htons(REMOTE_SERVER_PORT);
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd<0)
{
printf("%s:cannot open socket \n",argv[0]);
exit(1);
}
cli_Addr.sin_family = AF_INET;
cli_Addr.sin_addr.s_addr=htonl(INADDR_ANY);
cli_Addr.sin_port =htons(0);
rc = bind(sd,(struct sockaddr *) &cli_Addr,sizeof(cli_Addr));
if(rc<0)
{
printf("%s:cannot bind port number %d\n",argv[0],LOCAL_SERVER_PORT);
exit(1);
}
for(i=2;i
{
rc = sendto(sd,argv[i],strlen(argv[i]+1,0,(struct sockaddr *)&remote_Serv_Addr,sizeof(remote_Serv_Addr));
if(rc<0)
{
printf("%s:cannot send data %d\n",argv[0],i-1);
close(sd);
exit(1);
}
}
}
阅读(1167) | 评论(0) | 转发(0) |