10.19作业

搭建简单的服务器和客户端

服务器

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8888
#define IP "192.168.21.140"
#define ERR_MSG(msg) {printf("line=%d ",__LINE__);perror("msg");}
int main(int argc, const char *argv[])
{
	int sfd=socket(AF_INET,SOCK_STREAM,0);//AF_INET选择IPV4,SOCK_STREAM选择TCP,0是默认
	if (sfd<0)
	{
		ERR_MSG("socket");
		return -1;
	}
	struct sockaddr_in sin;    
	sin.sin_family=AF_INET;   	//代表选择的是IPV4
	sin.sin_port=ntohs(PORT);      //端口的网络字节序
	sin.sin_addr.s_addr=inet_addr(IP);   //IP的网络字节序
	if (bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
	{
		ERR_MSG("bind");
		return -1;
	}
	if (listen(sfd,128)<0)
	{
		ERR_MSG("listen");
		return -1;
	}
	struct sockaddr *connection_done;    //存储已连接的客户端
	socklen_t len=sizeof(*connection_done);
	int cfd=accept(sfd,connection_done,&len);
	if (cfd<0)
	{
		ERR_MSG("accept");
		return -1;
	}
	printf("客户端已连接\n");
	char buf[256]="";
	ssize_t res=999;
	while(res!=0)
	{
		res=recv(cfd,buf,128,0);
		if (res<0)
		{
			ERR_MSG("recv");
			return -1;
		}
		printf("%s",buf);
		bzero(buf,sizeof(buf));
	}
	printf("客服端已关闭\n");
	close(cfd);
	close(sfd);
	return 0;
}

客户端

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8888
#define IP "192.168.21.140"
#define ERR_MSG(msg) {printf("line=%d\n",__LINE__);perror("msg");}
int main(int argc, const char *argv[])
{
	int sfd=socket(AF_INET,SOCK_STREAM,0);//AF_INET选择IPV4,SOCK_STREAM选择TCP,0是默认
	if (sfd<0)
	{
		ERR_MSG("socket");
		return -1;
	}
	struct sockaddr_in sin;    
	sin.sin_family=AF_INET;   	//代表选择的是IPV4
	sin.sin_port=ntohs(PORT);      //端口的网络字节序
	sin.sin_addr.s_addr=inet_addr(IP);   //IP的网络字节序




if(	connect(sfd,(struct sockaddr *)&sin,sizeof(sin))!=0)
{
	ERR_MSG("connect");
	return -1;

} 
printf("链接服务器成功\n");
	char buf[256]="1";
	ssize_t res=999;
	while(res!=0)
	{
		fgets(buf,128,stdin);
		if (strcmp(buf,"quit")==0)
		{
			return -1;
		}
		send(sfd,buf,128,0);
		if (res<=0)
		{
			ERR_MSG("recv");
			return -1;
		}
		bzero(buf,sizeof(buf));
	}
	close(sfd);
	return 0; 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值