#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 4950
#define MAXBUFLEN 1024
int main(void)
{
int sockfd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int addr_len,numbytes;
char buf[MAXBUFLEN];
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket fail\n");
exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
memset(&(my_addr.sin_zero),'\0',8);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind fail\n");
exit(1);
}
while(1)
{
addr_len=sizeof(struct sockaddr);
if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN,0,
(struct sockaddr*)&their_addr,&addr_len))==-1)
{
perror("recvfrom fail\n");
exit(1);
}
buf[numbytes]='\0';
printf("%s says:%s",inet_ntoa(their_addr.sin_addr),buf);
}
close(sockfd);
return 0;
}
heimanba 于 2011-10-23 00:20:15发表:
3# tbamboo118
想了解的话,去找本环境编程的书来看,看完就都懂了。其实不难理解。。
aokang 于 2011-10-22 15:07:09发表:
求指导
tbamboo118 于 2011-10-22 14:19:03发表:
大神,求解释 ...
juzixiangchang 于 2008-09-03 16:06:13发表:
客户端:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 4950
#define MAXBUFLEN 1024
void sigchld_handler(int s)
{
while(wait(NULL)>0);
}
int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in their_addr;
struct hostent *he;
int numbytes;
char send_buf[MAXBUFLEN];
struct sigaction sa;
if(argc!=2)
{
fprintf(stderr,"usage:talker hostname\n");
exit(1);
}
if((he=gethostbyname(argv[1]))==NULL)
{
perror("gethostbyname fail\n");
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket fail\n");
exit(1);
}
while(1)
{
char *ptr;
their_addr.sin_family=AF_INET;
their_addr.sin_port=htons(MYPORT);
their_addr.sin_addr=*((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero),'\0',8);
printf("send to server:");
ptr=send_buf;
sa.sa_handler=sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags=SA_RESTART;
if(sigaction(SIGPIPE,&sa,NULL)==-1)
{
perror("sigaction fail\n");
exit(1);
}
do
{
*ptr=getchar();
ptr++;
}while(*(ptr-1)!='\n');
*ptr='\0';
if((numbytes=sendto(sockfd,send_buf,strlen(send_buf),0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr)))==-1)
{
perror("sendto fail\n");
exit(1);
}
}
close(sockfd);
return 0;
}