#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>//struct sockaddr_in
#include<arpa/inet.h>// inet_pton
#include<strings.h>
#include <unistd.h>
int main()
{
//1创建一个监听套接字
int sockfd=socket(AF_INET,SOCK_STREAM,0);
//2使用bind函数 给监听套接字 绑定固定的ip以及端口
struct sockaddr_in my_addr;
bzero(&my_addr,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(8000);
my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
bind(sockfd,(struct sockaddr *)&my_addr,sizeof(my_addr));
//3使用listen创建链接队列
listen(sockfd,10);
//4使用accpet函数从连接队列中 提取已完成的连接,得到已知套接字
//函数内部赋值不用清空,人为赋值需要清空
struct sockaddr_in cli_addr;
socklen_t cli_len=sizeof(cli_addr);
int new_fd=accept(sockfd,(struct sockaddr *)&cli_addr,&cli_len);
char ip[16]="";
inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,16);
printf("客户端:%s:%hu连接了服务器\n",ip,ntohs(cli_addr.sin_port));
//new_fd代表的是客户端的连接 cli_addr是存储客户端的信息(因为有很多客户端连接)
//5获取客户端的请求,以及回应客户端
char buf[128]="";
recv(new_fd,buf ,sizeof(buf),0);
printf("客户端的请求为:%s\n",buf);
send(new_fd,"lll",strlen("lll"),0);
//6关闭已连接套接字
close(new_fd);
///7关闭监听套接字
close(sockfd);
return 0;
}
tcp服务端代码
最新推荐文章于 2024-06-19 19:07:05 发布