#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <stdlib.h>
#define SA struct sockaddr
int main(int argc, const char *argv[])
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
perror("fail to socket");
exit(1);
}
struct sockaddr_in myaddr,peeraddr;
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(50000);
myaddr.sin_addr.s_addr=inet_addr("0.0.0.0");
socklen_t len=sizeof(peeraddr);
char buf[128];
//bind
int ret_bind=bind(sockfd,(SA*)&myaddr,sizeof(myaddr));
if(ret_bind<0)
{
perror("fail to bind");
exit(1);
}
int ret_lis=listen(sockfd,5);
if(ret_lis<0)
{
perror("fail to listen ");
exit(1);
}
while(1)
{
bzero(&peeraddr,len);
int confd=accept(sockfd,(SA*)&peeraddr,&len);
if(confd<0)
{
perror("fail to accept");
exit(1);
}
printf("%s:%d(fd=%d) is connected\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port),confd);
while(1)
{
//recv read
int ret_recv=recv(confd,buf,sizeof(buf),0);
if(ret_recv<0)
{
perror("fail to recv");
exit(1);
}
else if(ret_recv==0)//瀵规柟閫€鍑� 锛屾垜浠繑鍥炰笂涓€灞傚惊鐜紝缁х画鐩戝惉
{
printf("peer is shutdown!\n");
close(confd);
break;
}
else//鏀跺埌鏁版嵁鍐呭 echo鍥炲幓
{
printf("buf:%s\n",buf);
send(confd,buf,strlen(buf),0);
}
}
}
return 0;
}