Linux:简单的回射服务器

/ Linux / 没有评论 / 1939浏览

绝对正确

客户端

#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define ERR_EXIT(m)do{perror(m);exit(EXIT_FAILURE);}while(0)

int main(void)
{
	int sock;
	if((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) <0)
	{
		ERR_EXIT("socket");
	}
	struct sockaddr_in servaddr;
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(5188);

    //servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //inet_aton("127.0.0.1",&servaddr.sin_addr);
	
	if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0)
	{
       ERR_EXIT("connect");
	}

    char sendbuf[1024] = {0};
	char recvbuf[1024] = {0};
	while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL)
	{
		int n;
		write(sock,sendbuf,strlen(sendbuf));

		if((n = read(sock,recvbuf,sizeof(recvbuf))) > 0)//sizeof改成strlen读取错误
		{
			fputs(recvbuf,stdout);
			memset(sendbuf,0,sizeof(sendbuf));
			memset(recvbuf,0,sizeof(recvbuf));
		}
		else
		{
             fputs("error",stdout);
		}
		
	}
	close(sock);
    return 0;
}

服务端

#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define ERR_EXIT(m)do{perror(m);exit(EXIT_FAILURE);}while(0)

int main(void)
{
	int listenfd;
	if((listenfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) <0)
		//listenfd = socket(PF_INET,SOCK_STREAM,0);
	{
		ERR_EXIT("socket");
	}
	struct sockaddr_in servaddr;
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(5188);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    //servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //inet_aton("127.0.0.1",&servaddr.sin_addr);
	
    //开启地址重复利用(在TIME_WAIT未消失的情况下,允许服务器重启)
    int on = 1;
    if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)) < 0)
		ERR_EXIT("setsockopt");

    if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0)
		ERR_EXIT("bind");
    
    if(listen(listenfd,SOMAXCONN) < 0)
		ERR_EXIT("listen");
	
	struct sockaddr_in peeraddr;
	socklen_t peerlen = sizeof(peeraddr);
	
	int conn;
	if((conn = accept(listenfd,(struct sockaddr*)&peeraddr, &peerlen)) < 0)
        ERR_EXIT("accept");
    
	char recvbuf[1024];
	while(1)
	{
        memset(recvbuf,0,sizeof(recvbuf));
		int ret = read(conn,recvbuf,sizeof(recvbuf));
		fputs(recvbuf,stdout);
		int n;
		if((n = write(conn,recvbuf,ret)) < 0)
		{
			fputs("error",stdout);
		}
	}

	close(conn);
	close(listenfd);
    return 0;
}