Client.c
1 /*interactionsocket/client.c2 * Realize interactive input and output of terminal and server side3 */4#include <stdio.h>5#include <stdlib.h>6#include <string.h>7#include <unistd.h>8#include <sys/types.h>9#include <sys/socket.h>Ten#include <netinet/inch.h> One#include <netdb.h> A - #defineMAXLINE 80 - #definePortnum 12345 the - intMainvoid) { - intsock, Len; - structsockaddr_in saddr; + structHostent *HP; - CharBuf[maxline]; + CharRequest[maxline]; A CharHostname[bufsiz]; at -Sock=socket (Af_inet, Sock_stream,0); - if(sock==-1) Exit (-1); - -Bzero ((void*) &saddr,sizeof(SADDR)); - //Inet_pton (af_inet, "127.0.0.1", (void*) &saddr.sin_addr); in gethostname (hostname, bufsiz); -hp=gethostbyname (hostname); toBcopy (Hp->h_addr, (void*) &saddr.sin_addr, hp->h_length); +saddr.sin_port=htons (portnum); -saddr.sin_family=af_inet; the *Connect (sock, (structSOCKADDR *) &saddr,sizeof(SADDR)); $ while(Fgets (buf, MAXLINE, stdin)! =NULL) {Panax Notoginseng Write (sock, buf, strlen (BUF)); -len=Read (sock, buf, MAXLINE); the if(len==0) +printf"The other side have been closed"); A Else the Write (Stdout_fileno, buf, Len); + } - Close (sock); $ return 1; $}
Server.c
1 /*interaction/server.c2 */3#include <stdio.h>4#include <stdlib.h>5#include <netinet/inch.h>6#include <sys/types.h>7#include <sys/socket.h>8#include <string.h>9#include <netdb.h>Ten One #defineMAXLINE 80 A #defineServ_port 12345 - #defineBACKLOG 20 - intMainvoid ) { the intsock, CONNFD; - structsockaddr_in saddr, cliaddr; - structHostent *HP; - socklen_t Cliaddr_len; + CharBuf[maxline]; - CharStr[maxline]; + CharHostname[bufsiz]; A inti, N; at -Sock=socket (Pf_inet, Sock_stream,0); - if(sock==-1) -Exit (-1); -Bzero ((void*) &saddr,sizeof(SADDR)); - //saddr.sin_addr.s_addr=htonl (inaddr_any); in gethostname (hostname, bufsiz); -hp=gethostbyname (hostname); toBcopy (Hp->h_addr, (void*) &saddr.sin_addr, hp->h_length); +saddr.sin_family=af_inet; -saddr.sin_port=htons (serv_port); the if(Bind (sock, (structsockaddr*) &saddr,sizeof(SADDR)) ==-1) *Exit (-1); $ if(Listen (sock, BACKLOG) ==-1)Panax NotoginsengExit (-1); -printf"Accepting connections...\n"); the while(1) { +cliaddr_len=sizeof(CLIADDR); AConnfd=accept (sock, (structsockaddr*) &cliaddr, &Cliaddr_len); the while(1) { +n=Read (CONNFD, buf, MAXLINE); - if(n==0){ $printf"The other side have been closed.\n"); $ Break; - } - //printf ("received from%s at PORT%d\n", Inet_ntop (Af_inet, &cliaddr.sin_addr, str, sizeof (STR)), Ntohs ( Cliaddr.sin_port)); the for(i=0; i<n; i++) -buf[i]=ToUpper (Buf[i]);Wuyi Write (CONNFD, buf, n); the } - Close (CONNFD); Wu } -}
Linux_c socket Server and Client interaction program (input lowercase converted to uppercase)