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/inch.h>7#include <unistd.h>8 9 intMain () {Ten /*Socket*/ One intSoc_ser_l=socket (Pf_inet,sock_stream,0); A - /*creat server sockaddr_in*/ - structsockaddr_in ser_addr; theser_addr.sin_family=af_inet; -Ser_addr.sin_addr.s_addr=htonl (inaddr_any); -Ser_addr.sin_port=htons (8888); -memset (Ser_addr.sin_zero,0,8); + - /*bind connect socket and Ip/port*/ + if(Bind (soc_ser_l, (structsockaddr*) &ser_addr,sizeof(SER_ADDR)) ==-1) A { atprintf"bind error"); - return 0; - } - - /*Listen*/ - if(Listen (soc_ser_l, -)==-1) in { -printf"Listen error"); to return 0; + } - /*creat Items*/ the intsoc_ser_t; * structsockaddr_in cli_addr; $ while(1){Panax Notoginseng /*Accept*/ - intlen=sizeof(SER_ADDR); theSoc_ser_t=accept (soc_ser_l, (structSOCKADDR *) &cli_addr,&len); + if(soc_ser_t==-1){ APerror ("Accept Error"); theExit1); + } - $ /*recv Data*/ $ Charrecv_buf[255]; - intRET=RECV (Soc_ser_t,recv_buf,255,0); - if(ret>0){ therecv_buf[ret]=' /'; -printf"Server recv:");Wuyiprintf"%s\n", recv_buf); the } - Wu /*Send Data*/ - Charsend_msg_str[ -]; Aboutprintf"Server send:"); $Fgets (SEND_MSG_STR, -, stdin); -* (STRCHR (SEND_MSG_STR,'\ n'))=' /'; -Send (Soc_ser_t,send_msg_str,strlen (SEND_MSG_STR),0); - Close (soc_ser_t); A } + the Close (soc_ser_l); - return 0; $}
1#include <stdio.h>2#include <string.h>3#include <sys/types.h>4#include <sys/socket.h>5#include <netinet/inch.h>6#include <arpa/inet.h>7#include <unistd.h>8 9 intMain () {Ten /*creat Client Socket*/ One intSoc_cli=socket (Pf_inet,sock_stream,0); A /*creat server sockaddr_in*/ - structsockaddr_in ser_addr; -ser_addr.sin_family=pf_inet; theSER_ADDR.SIN_ADDR.S_ADDR=INET_ADDR ("192.168.195.129"); -Ser_addr.sin_port=htons (8888);//8888 Port number has no "" -memset (Ser_addr.sin_zero,0,8); - + - /*Connect*/ + if(Connect (SOC_CLI,structsockaddr*) &ser_addr,sizeof(SER_ADDR)) ==-1){ Aprintf"Connect Error"); at return 0; - } - - - /*Send*/ - Charcli_send_str[ -]; inprintf"Client Send:"); -Fgets (CLI_SEND_STR, -, stdin); to* (STRCHR (CLI_SEND_STR,'\ n'))=' /'; + -Send (Soc_cli,cli_send_str,strlen (CLI_SEND_STR),0); the * /*recv*/ $ Charcli_recv[255];Panax Notoginseng intRET=RECV (SOC_CLI,CLI_RECV,255,0); - if(ret>0){ thecli_recv[ret]=' /'; +printf"Client recv:"); Aprintf"%s\n", CLI_RECV); the } + - Close (SOC_CLI); $ return 0; $}
Simple implementation of server/client C code