/* Service-side program */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
int main (void)
{
int SOCKFD,RET,NEWFD;
int Readlen;
int Theirlen;
Char recv[100]={0};
struct sockaddr_in myaddr;
struct sockaddr_in theiraddr;
if ((Sockfd=socket (af_inet,sock_stream,0)) < 0)
{
printf ("Socket failed (%s) \ n", Strerror (errno));
Exit (0);
}
memset (&myaddr,0,sizeof (MYADDR));
Myaddr.sin_family=af_inet;
Myaddr.sin_port =htons (3490);
Myaddr.sin_addr.s_addr=htonl (Inaddr_any);
if ((Ret=bind (SOCKFD, (struct sockaddr *) &myaddr,sizeof (MYADDR))) < 0)
{
printf ("Bind failed\n");
Exit (0);
}
if ((Ret=listen (sockfd,10)) < 0)
{
printf ("Listen failed\n");
Exit (0);
}
Theirlen=sizeof (THEIRADDR);
if ((Newfd=accept (SOCKFD, (struct sockaddr *) &theiraddr,&theirlen) < 0)
{
printf ("Accept failed\n");
Exit (0);
}
while (1)
{
memset (recv,0,sizeof (recv));
Readlen=read (newfd,recv,sizeof (recv));
Fputs (recv,stdout);
Write (Newfd,recv,readlen);
}
Close (NEWFD);
Close (SOCKFD);
return 0;
}
/* Client program */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
int main (void)
{
int Sockfd,ret;
int Readlen;
Char send[100]={0};
Char recv[100]={0};
struct sockaddr_in myaddr;
if ((Sockfd=socket (af_inet,sock_stream,0)) < 0)
{
printf ("Socket failed\n");
Exit (1);
}
memset (&myaddr,0,sizeof (MYADDR));
Myaddr.sin_family=af_inet;
Myaddr.sin_port =htons (3490);
MYADDR.SIN_ADDR.S_ADDR=INET_ADDR ("192.168.1.110");
if ((Ret=connect (SOCKFD, (struct sockaddr *) &myaddr,sizeof (MYADDR))) < 0)
{
printf ("Connect failed\n");
Exit (1);
}
while (1)
{
memset (recv,0,sizeof (recv));
memset (send,0,sizeof (send));
if (Fgets (send,sizeof (send), stdin)!=null)
{
Write (sockfd,send,sizeof (send));
Read (sockfd,recv,sizeof (recv));
Fputs (recv,stdout);
}
}
Close (SOCKFD);
return 0;
}
Code complete, can run straight
Simple implementation of client server-side interconnect communication