作业1
题目
TCP模型实现
结果
代码
server_tcp.c
#include <arpa/inet.h>
#include <netinet/in.h> // sockaddr_in申明
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define IP "172.27.56.253"
#define PORT 5000
#define MAXIMUN_LENGTH 128
#define ERR_MSG(msg) \
{ \
perror(msg); \
printf("error in line %d\n", __LINE__); \
}
int main(int argc, char const *argv[])
{
// 1. 创建套接字文件
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
ERR_MSG("socket");
return -1;
}
// // 允许端口号被重复使用
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
ERR_MSG("setsockopt");
return -1;
}
// 2. 文件绑定ip、端口
struct sockaddr_in addr_server;
addr_server.sin_family = AF_INET; // IPV4协议
addr_server.sin_addr.s_addr = inet_addr(IP); // IP地址(网络字节序)
addr_server.sin_port = htons(PORT); // 端口(网络字节序)
int bind_ret = bind(sockfd, (struct sockaddr *)&addr_server, sizeof(addr_server));
if(bind_ret < 0){
ERR_MSG("socket");
return -1;
}
// 3. listen外部请求
listen(sockfd, MAXIMUN_LENGTH);
if(bind_ret < 0){
ERR_MSG("socket");
return -1;
}else{
printf("server is running...\n");
}
// 4. accept接收外部请求
struct sockaddr_in addr_client;
socklen_t addr_client_len;
int recfd = accept(sockfd, (struct sockaddr *)&addr_client,&addr_client_len);
printf("client has connected\n");
// 5. recv、send消息收发
char buf[1024] = {0};
ssize_t n;
while (1) {
// 接收
n = recv(recfd, buf, sizeof(buf), 0);
if (n > 0) {
printf("收到来自 %s 的:%s\n", inet_ntoa(addr_client.sin_addr),buf);
}else if (n < 0){
ERR_MSG("recv");
return -1;
}else{
printf("%s 退出连接\n", inet_ntoa(addr_client.sin_addr));
break; //无内容输入退出
}
}
// 6. close 关闭套接字文件
close(recfd);
close(sockfd);
return 0;
}
client_tcp.c
#include <arpa/inet.h>
#include <netinet/in.h> // sockaddr_in申明
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define IP "172.27.56.253"
#define PORT 5000
#define MAXIMUN_LENGTH 128
int main(int argc, char const *argv[])
{
// 1. 创建套接字文件
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// 2. 连接服务器ip、端口
struct sockaddr_in addr_server;
addr_server.sin_family = AF_INET; // IPV4协议
addr_server.sin_addr.s_addr = inet_addr(IP); // IP地址(网络字节序)
addr_server.sin_port = htons(PORT); // 端口(网络字节序)
connect(sockfd,(struct sockaddr *)&addr_server,sizeof(addr_server));
printf("connect success\n");
// 3. recv、send消息收发
char buf[1024] = {0};
while (1)
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
// 发送
send(sockfd,buf,sizeof(buf),0);
}
// 6. close 关闭套接字文件
close(sockfd);
return 0;
}