简单的网络通信程序 TCP

/*server*/
#include 
#include 
#include 
#include 
#include 
#include 

int main(){
  int sockfd = socket(PF_INET,SOCK_STREAM,0);
	if(sockfd == -1) perror("socket"),exit(-1);
  struct sockaddr_in addr;
  addr.sin_family = PF_INET;
	addr.sin_port = htons(2222);
	addr.sin_addr.s_addr = 
		inet_addr("172.40.0.10");
  int res = bind(sockfd,
		(struct sockaddr*)&addr,sizeof(addr));
	if(res == -1) perror("bind"),exit(-1);
	printf("bind ok\n");
  listen(sockfd,100);//4 监听
	struct sockaddr_in from;
	socklen_t len = sizeof(from);
  int fd = accept(sockfd,//5 等待客户端的连接
		(struct sockaddr*)&from,&len);//阻塞函数
  if(fd == -1) perror("accpet"),exit(-1);
	printf("%s连接上来\n",
		inet_ntoa(from.sin_addr));
  char buf[100] = {};
  read(fd,buf,sizeof(buf));//先读
	printf("%s\n",buf);
	write(fd,"welcome",7);//后写
	close(fd); 
	close(sockfd);
} 

/*client*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(){
  int sockfd = socket(PF_INET,SOCK_STREAM,0);
	if(sockfd == -1) perror("socket"),exit(-1);
	struct sockaddr_in addr;
  addr.sin_family = PF_INET;
	addr.sin_port = htons(2222);
  addr.sin_addr.s_addr = //取结构中的成员
		inet_addr("172.40.0.10");//转换函数
	int res = connect(sockfd,
		(struct sockaddr*)&addr,sizeof(addr));
  char buf[100] = {};
	char ret[100] = {};
	while(1){
		printf("请输入聊天信息\n");
		scanf("%s",buf);
	  write(sockfd,buf,strlen(buf));
		if(!strcmp(buf,"bye")) break;
	  read(sockfd,ret,sizeof(ret));
	  printf("%s\n",ret);
		memset(buf,0,strlen(buf));//清0
		memset(ret,0,strlen(ret));//清0
	}
	close(sockfd);
}



 
  

你可能感兴趣的:(C语言编程)