点击(此处)折叠或打开
- #include "apue.h"
- #include <netdb.h>
- /******************************客户端进程(Client.c)**********************************************/
- #include <sys/socket.h>
- #define BUFLEN 128
- #define QLEN 10
- int
- main(void)
- {
- struct sockaddr_in ServerAdd;
- int sockfd,err,clfd,n;
- char buf[256];
- in_addr_t *hostip;
- hostip=malloc(256);
- /**************初始化服务端地址*****************/
- ServerAdd.sin_family=AF_INET;
- ServerAdd.sin_port=htons(6666);
- memset(ServerAdd.sin_zero,0,8);
- if((err=inet_pton(AF_INET,"127.0.0.1",(void*)hostip))!=1)
- printf("inet_pton error\n");
- ServerAdd.sin_addr.s_addr=*hostip;
- /***********************************************/
- if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)//创建套接字描述符
- printf("sock error\n");
- if(connect(sockfd,(struct sockaddr*)&ServerAdd,sizeof(struct sockaddr))<0)//与服务器建立连接
- printf("connect error\n");
- while((n=recv(sockfd,buf,256,0))>0)//等待接收服务器数据
- write(STDOUT_FILENO,buf,n);
- exit(0);
- }
点击(此处)折叠或打开
- /****************************服务器端进程(Server.c)***************************************/
- #include "apue.h"
- #include <netdb.h>
- #include <sys/socket.h>
- #include <errno.h>
- #define BUFLEN 128
- #define QLEN 10
- int
- main(void)
- {
- struct sockaddr_in ServerAdd;
- int sockfd,err,clfd;
- char buf[]="hello client\n";
- in_addr_t *hostip;
- hostip=malloc(256);
- /*********************初始化服务器端地址*****************************/
- ServerAdd.sin_family=AF_INET;
- ServerAdd.sin_port=htons(6666);
- memset(ServerAdd.sin_zero,0,8);
- if((err=inet_pton(AF_INET,"127.0.0.1",(void*)hostip))!=1)
- printf("inet_pton error\n");
- ServerAdd.sin_addr.s_addr=*hostip;
- /**************************************************/
- if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)//创建套接字描述符
- printf("sock error\n");
- if(bind(sockfd,(struct sockaddr*)&ServerAdd,sizeof(struct sockaddr))<0)//地址与描述符绑定
- printf("bind error\n");
- if(listen(sockfd,10)<0)//开始监听
- printf("listen error\n");
- if((clfd=accept(sockfd,NULL,NULL))<0)//阻塞,等待连接
- printf("accept error:%s\n",strerror(errno));
- send(clfd,buf,strlen(buf),0);//有链接到达后发送数据
- close(clfd);
- }