if (ret==-1) { printf("failed when binding\n"); exit(-1); } //listen.
if (listen(sockfd,BACKLOG)==-1) { printf("failed when listening\n"); exit(-1); } printf("server listening...wait for connect...\n"); while (1) { sin_size=sizeof(struct sockaddr); con_fd=accept(sockfd,(struct sockaddr*)&their_addr,&sin_size); if (con_fd<0) { printf("failed when accepting\n"); exit(-1); } //recv a string from client and print the string.
if (recv(con_fd,buf,sizeof(buf),0)==-1) { printf("failed when receiving the string\n"); exit(-1); } printf(" received form client...%s\n",buf); //send the buf string to client and print it.
if (send(con_fd,&buf,sizeof(buf),0)==-1) { printf("failed when sending the string"); exit(-1); } printf(" send to client...%s\n",buf); close(con_fd); } close(sockfd); exit(0); }
int main(int argc,char *argv[]) { int sockfd,con_fd,numbytes,ret,pid; struct sockaddr_in server_addr; struct hostent *their_addr; int sin_size; int lis; char buf[256]; char *str="Default test string.\n"; char *ip="192.192.192.190\n"; //if you input the new host ip after the command
//then change the default local host ip address.
if (argc<2) printf("default local host : 192.192.192.190 , or you can input one after the command.\n"); else { ip=argv[1]; printf("local host ip = %s\n",ip); }
bzero(&(server_addr.sin_zero),8); sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd==-10) { printf("failed when creating\n"); exit(-1); }
//connect the server.
if (connect(sockfd,(void*)&server_addr,sizeof(server_addr))==-1) { printf("failed when connecting\n"); exit(-1); }
//send the default string to server.
printf(" send to server...%s\n",str); if (send(sockfd,str,strlen(str),0)==-1) { printf("failed when sending\n"); exit(-1); } //receive a string from server.
if (recv(sockfd,buf,sizeof(buf),0)==-1) { printf("failed when receiving\n"); exit(-1); }
printf(" response from server...%s\n",buf); close(sockfd); }