Bootstrap

2024.8.19

#include <stdio.h>
#include <sys/types.h>        
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>


int main()
{
	//1.创建套接字
	int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
			//网际协议,套接字类型TCP选择流式套接字
	if(-1 == sock_fd)
	{
		perror("creat sock_fd failed");
		return -1;
	}		
	//2.绑定服务器的IP地址+端口号
	
	//定义结构体
	struct sockaddr_in serve,client;
	serve.sin_family = AF_INET;//地址族成员
	serve.sin_port =  htons(10086);//0-------65535 (0----5000,大型企业,5000-----10000,留给将来的大型企业,10000-----65535,才是留给我们的)
	serve.sin_addr.s_addr =  inet_addr("192.168.124.68");//需要把点分式字符串转换为无符号的32位网络地址in_addr_t,
	//绑定函数
	int ret = bind(sock_fd, (struct sockaddr *)&serve, sizeof(serve));
	if(ret == -1)
	{
		perror("bind failed");
	}
	
	//3.监听
	int listen_ret = listen(sock_fd, 4);//可以设置监听的套接字的最大个数
	
	//4.等待连接
	printf("等待连接....\n");
	int a = sizeof(client);
	int acc_fd = accept(sock_fd, (struct sockaddr *)&client, (socklen_t *)&a);//阻塞等待
	printf("连接成功!!!\n");
	
	
	char *buf = malloc(100);
	//5.畅聊
	while(1)
	{
		memset(buf,0,100);
		//接收消息
		int len=recv(acc_fd, buf, 100, 0);
		if(0==len)
		{
			break;
		}
		
		printf("客户端IP地址:%s,客户端口号:%d,消息:%s\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port),buf);
	}
	
}

#include <stdio.h>
#include <sys/types.h>        
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int sock_fd=socket(AF_INET,SOCK_STREAM,0);
    if(-1==sock_fd)
    {
        perror("创建失败");
        return -1;
    }
    struct sockaddr_in serve;
	serve.sin_family = AF_INET;//地址族成员
	serve.sin_port =  htons(10086);//0-------65535 (0----5000,大型企业,5000-----10000,留给将来的大型企业,10000-----65535,才是留给我们的)
	serve.sin_addr.s_addr =  inet_addr("192.168.124.68");
    int ret=connect(sock_fd,(struct sockaddr*)&serve,sizeof(serve));
    if(-1==ret)
    {
        perror("连接失败");
    }
    char *buf=malloc(100);
    while(1)
    {
        memset(buf,0,100);
        fgets(buf,100,stdin);
        send(sock_fd,buf,strlen(buf)-1,0);
    }
}

;