Service side:
Hello_server.c
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<arpa/inet.h>#include<sys/socket.h>voidError_handling (Char*message);intMainintargcChar*argv[]) { intServ_sock; intClnt_sock; structsockaddr_in serv_addr; structsockaddr_in clnt_addr; Socklen_t clnt_addr_size; CharMessage[] ="Hello Master haku!"; if(ARGC! =2) {printf ("Usage:%s <port>\n", argv[0]); Exit (1); } Serv_sock= Socket (Af_inet, Sock_stream,0); if(Serv_sock = =-1) error_handling ("sock () error"); memset (&SERV_ADDR,0,sizeof(SERV_ADDR)); Serv_addr.sin_family=af_inet; Serv_addr.sin_addr.s_addr=htonl (Inaddr_any); Serv_addr.sin_port= Htons (Atoi (argv[1])); if(Bind (Serv_sock, (structsockaddr*) &serv_addr,sizeof(SERV_ADDR)) == -1) error_handling ("bind () error"); if(Listen (Serv_sock,5) == -1) error_handling ("Listen () Error"); Clnt_addr_size=sizeof(CLNT_ADDR); Clnt_sock= Accept (Serv_sock, (structsockaddr*) &clnt_addr, &clnt_addr_size); if(Clnt_sock = =-1) error_handling ("Accept () error"); Write (clnt_sock, message,sizeof(message)); Close (Clnt_sock); Close (Serv_sock); return 0;}voidError_handling (Char*message) {fputs (message, stderr); FPUTC ('\ n', stderr); Exit (1);}
Client:
Hello_client.c
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<unistd.h>#include<arpa/inet.h>#include<sys/socket.h>voidError_handling (Char*message);intMainintargcChar*argv[]) { intsock; structsockaddr_in serv_addr; Charmessage[ -]; intStr_len; if(ARGC! =3) {printf ("Usage:%s <IP> <port>\n", argv[0]); Exit (1); } sock= Socket (Af_inet, Sock_stream,0); if(Sock = =-1) error_handling ("sock () error"); memset (&SERV_ADDR,0,sizeof(SERV_ADDR)); Serv_addr.sin_family=af_inet; Serv_addr.sin_addr.s_addr= Inet_addr (argv[1]); Serv_addr.sin_port= Htons (Atoi (argv[2])); if(Connect (sock,structsockaddr*) &serv_addr,sizeof(SERV_ADDR)) == -1) error_handling ("Connect () error!"); Str_len= Read (sock, message,sizeof(message)-1); if(Str_len = =-1) error_handling ("read () error!"); printf ("Message from server:%s\n", message); Close (sock); return 0;}voidError_handling (Char*message) {fputs (message, stderr); FPUTC ('\ n', stderr); Exit (1);}
Operating mode
Service side:
GCC Hello_server.c-o hserver
./hserver 9999
Client:
GCC Hello_client.c-o hclient
./hclient 127.0.0.1 9999
Run results
Client:
Message from Server:hello Master haku!
TCP/TP Programming-A simple Linux under C write Socket Server client program