/*服务端程序*/
#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;
}
/*客户端程序*/
#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;
}
代码完整,可直运行
原文地址:https://www.cnblogs.com/cyyljw/p/9188590.html