笔记脑图
作业:
1、将虚拟机调整到桥接模式联网。
2、TCP客户端服务器实现一遍。
服务器
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
#define BACKLOG 20
int main(int argc, const char *argv[])
{//创建int oldfd=socket(AF_INET,SOCK_STREAM,0);if(oldfd==-1){perror("socket");return -1;}//绑定struct sockaddr_in server={.sin_family=AF_INET,.sin_port=htons(PORT),.sin_addr.s_addr=inet_addr(IP),};if(bind(oldfd,(struct sockaddr *)&server,sizeof(server))==-1){perror("bind");return -1;}//监听if(listen(oldfd,BACKLOG)==-1){perror("listen");return -1;}//接收通信struct sockaddr_in client;socklen_t client_len=sizeof(client);int newfd;newfd=accept(oldfd,(struct sockaddr *)&client,&client_len);if(newfd==-1){perror("accept");return -1;}printf("%s发来连接请求\n",inet_ntoa(client.sin_addr));//循环收发char buff[1024];while(1){memset(buff,0,sizeof(buff));//int len=read(newfd,buff,sizeof(buff));int len=recv(newfd,buff,sizeof(buff),0);if(len==0){printf("客户端下线\n");break;}printf("%s\n",buff);strcat(buff,"5201314");//write(newfd,buff,sizeof(buff));send(newfd,buff,sizeof(buff),0);}//关闭close(oldfd);close(newfd); return 0;
}
客户端
#include <stdio.h>
#include <string.h>
#include <myhead.h>
#define IP "192.168.60.44"
#define PORT 6666
int main(int argc, const char *argv[])
{//创建int oldfd=socket(AF_INET,SOCK_STREAM,0);if(oldfd==-1){perror("socket");return -1;}//连接服务器struct sockaddr_in server={.sin_family=AF_INET,.sin_port=htons(PORT),.sin_addr.s_addr=inet_addr(IP),};if(connect(oldfd,(struct sockaddr *)&server,sizeof(server))==-1){perror("connect");return -1;}//循环收发char buff[1024];while(1){fgets(buff,sizeof(buff),stdin);buff[strlen(buff)-1]='\0';send(oldfd,buff,sizeof(buff),0);int len=recv(oldfd,buff,sizeof(buff),0);if(len==0){printf("服务器意外退出\n");break;}printf("接收服务器的消息:%s\n",buff);}//关闭close(oldfd);return 0;
}