标签:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<sys/types.h> 5 #include<sys/socket.h> 6 #include<netinet/in.h> 7 #include <unistd.h> 8 9 int main() { 10 /* socket */ 11 int soc_ser_l=socket(PF_INET,SOCK_STREAM,0); 12 13 /* creat server sockaddr_in */ 14 struct sockaddr_in ser_addr; 15 ser_addr.sin_family=AF_INET; 16 ser_addr.sin_addr.s_addr=htonl(INADDR_ANY); 17 ser_addr.sin_port=htons(8888); 18 memset(ser_addr.sin_zero,0,8); 19 20 /* bind connect socket and ip/port */ 21 if(bind(soc_ser_l,(struct sockaddr*)&ser_addr,sizeof(ser_addr))==-1) 22 { 23 printf("bind error"); 24 return 0; 25 } 26 27 /* listen */ 28 if(listen(soc_ser_l,20)==-1) 29 { 30 printf("listen error"); 31 return 0; 32 } 33 /* creat items */ 34 int soc_ser_t; 35 struct sockaddr_in cli_addr; 36 while (1){ 37 /* accept */ 38 int len=sizeof(ser_addr); 39 soc_ser_t=accept(soc_ser_l,(struct sockaddr *)&cli_addr,&len); 40 if(soc_ser_t==-1){ 41 perror("accept error"); 42 exit(1); 43 } 44 45 /* recv data */ 46 char recv_buf[255]; 47 int ret=recv(soc_ser_t,recv_buf,255,0); 48 if(ret>0){ 49 recv_buf[ret]=‘\0‘; 50 printf("server recv:"); 51 printf("%s\n",recv_buf); 52 } 53 54 /* send data */ 55 char send_msg_str[100]; 56 printf("server send:"); 57 fgets(send_msg_str,100,stdin); 58 *(strchr(send_msg_str,‘\n‘))=‘\0‘; 59 send(soc_ser_t,send_msg_str,strlen(send_msg_str),0); 60 close(soc_ser_t); 61 } 62 63 close(soc_ser_l); 64 return 0; 65 }
1 #include<stdio.h> 2 #include<string.h> 3 #include<sys/types.h> 4 #include<sys/socket.h> 5 #include<netinet/in.h> 6 #include <arpa/inet.h> 7 #include <unistd.h> 8 9 int main(){ 10 /* creat client socket */ 11 int soc_cli=socket(PF_INET,SOCK_STREAM,0); 12 /* creat server sockaddr_in */ 13 struct sockaddr_in ser_addr; 14 ser_addr.sin_family=PF_INET; 15 ser_addr.sin_addr.s_addr=inet_addr("192.168.195.129"); 16 ser_addr.sin_port=htons(8888);//8888 port number has no "" 17 memset(ser_addr.sin_zero,0,8); 18 19 20 /* connect */ 21 if(connect(soc_cli,(struct sockaddr*)&ser_addr,sizeof(ser_addr))==-1){ 22 printf("connect error"); 23 return 0; 24 } 25 26 27 /* send */ 28 char cli_send_str[100]; 29 printf("client send:"); 30 fgets(cli_send_str,100,stdin); 31 *(strchr(cli_send_str,‘\n‘))=‘\0‘; 32 33 send(soc_cli,cli_send_str,strlen(cli_send_str),0); 34 35 /* recv */ 36 char cli_recv[255]; 37 int ret=recv(soc_cli,cli_recv,255,0); 38 if(ret>0){ 39 cli_recv[ret]=‘\0‘; 40 printf("client recv:"); 41 printf("%s\n",cli_recv); 42 } 43 44 close(soc_cli); 45 return 0; 46 }
标签:
原文地址:http://www.cnblogs.com/sslblog/p/5696041.html