Day31

广播

发送

#include <myhead.h>

#define ERR_MSG(msg) do{\
	fprintf(stderr, "line:%d %s\t%s", __LINE__, __FILE__, __func__);\
	perror(msg);\
}while(0)

#define IP "192.168.2.255"   //广播IP
#define PORT 6666            //1024~49151,网络字节序

int main(int argc, const char *argv[])
{
	//1> 创建报式套接字
	int cfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(cfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("create socket success sfd = %d __%d__\n", cfd, __LINE__);


	//设置允许广播
	int broad = 1;
	if(setsockopt(cfd, SOL_SOCKET, SO_BROADCAST, &broad, sizeof(broad)) < 0)
	{
		ERR_MSG("setsockop");
		return -1;
	}
	printf("broadcast success __%d__\n", __LINE__);

	//2> 填充接收方的地址信息结构体
	struct sockaddr_in sin;
	sin.sin_family      = AF_INET;        
	sin.sin_port        = htons(PORT);    
	sin.sin_addr.s_addr = inet_addr(IP);  

	char buf[128] = "";
	while(1)
	{
		//3> 发送数据
		printf("请输入>>>");
		fgets(buf, sizeof(buf), stdin);
		buf[strlen(buf)-1] = '\0';

		if(sendto(cfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
		{
			ERR_MSG("send");
			return -1;
		}
		printf("send success __%d__\n", __LINE__);
	}	

	//关闭套接字文件描述符
	close(cfd);
	return 0;
}

接收

#include <myhead.h>

#define ERR_MSG(msg) do{\
	fprintf(stderr, "line:%d %s %s", __LINE__, __FILE__, __func__);\
	perror(msg);\
}while(0)

#define IP "192.168.2.255"   //广播IP
#define PORT 6666            //1024~49151,网络字节序

int main(int argc, const char *argv[])
{
	//1> 创建报式套接字
	int sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("create socket success sfd = %d __%d__\n", sfd, __LINE__);

	//填充服务器的地址信息结构体
	struct sockaddr_in sin;
	sin.sin_family      = AF_INET;    
	sin.sin_port        = htons(PORT);    
	sin.sin_addr.s_addr = inet_addr(IP);  //广播IP

	//2> 绑定接收方的IP和端口
	if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
	{
		ERR_MSG("bind");
		return -1;
	}
	printf("bind success __%d__\n", __LINE__);

	char buf[128] = "";
	struct sockaddr_in cin;    //存储数据包从哪里来的
	socklen_t addrlen = sizeof(cin);
	while(1)
	{
		bzero(buf, sizeof(buf));
		//3> 接收数据
		if(recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cin, &addrlen) < 0)
		{
			ERR_MSG("recv");
			return -1;
		}
		printf("[%s:%d] : %s\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), buf);
		}	
	//关闭套接字文件描述符
	close(sfd);
	return 0;
}

组播

发送

#include <myhead.h>

#define ERR_MSG(msg) do{\
    fprintf(stderr, "line:%d: %s %s\n", __LINE__, __FILE__, __func__);\
    perror(msg);\
}while(0)

#define IP  "224.1.2.3"  
#define PORT 6666        

int main(int argc, const char *argv[])
{
    //创建报式套接字
    int cfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(cfd < 0)
    {
        ERR_MSG("socket");
        return -1;
    }
    printf("create socket success sfd=%d __%d__\n", cfd, __LINE__);
                                                     
    //接收方的地址信息结构体
    struct sockaddr_in sin;
    sin.sin_family      = AF_INET;
    sin.sin_port        = htons(PORT);
    sin.sin_addr.s_addr = inet_addr(IP); 
    
    char buf[128] = "";
    while(1)
    {
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf)-1] = 0;

        if(sendto(cfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
        {
            ERR_MSG("sendto");
            return -1;
        }
        printf("发送成功\n");
    }

    close(cfd);
    return 0;
}

接收

#include <unistd.h>

#define ERR_MSG(msg) do{\
    fprintf(stderr, "line:%d: %s %s\n", __LINE__, __FILE__, __func__);\
    perror(msg);\
}while(0)                                                                                 

#define GRP_IP  "224.1.2.3"    
#define LOL_IP  "192.168.2.194"
#define PORT 6666          

int main(int argc, const char *argv[])
{
    //创建报式套接字
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sfd < 0)
    {
        ERR_MSG("socket");
        return -1;
    }
    printf("create socket success sfd=%d __%d__\n", sfd, __LINE__);

    //加入多播组
    struct ip_mreqn mq;
    mq.imr_multiaddr.s_addr = inet_addr(GRP_IP);    
    mq.imr_address.s_addr   = inet_addr(LOL_IP);   
    mq.imr_ifindex          = 2;      

    if(setsockopt(sfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mq, sizeof(mq)) < 0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("加入多播组 %s 成功 __%d__\n", GRP_IP, __LINE__);

    //填充接收方的地址信息结构体
    struct sockaddr_in sin;
    sin.sin_family      = AF_INET;
    sin.sin_port        = htons(PORT);
    sin.sin_addr.s_addr = inet_addr(GRP_IP);    //组播IP 224.0.0.0-239.255.255.255

    //绑定地址信息结构体
    if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("bind success __%d__\n", __LINE__);

    char buf[128] = "";
    struct sockaddr_in cin;         //存储数据包是从哪里来的
    socklen_t addrlen = sizeof(cin);
    while(1)
    {
        bzero(buf, sizeof(buf));
        //接收数据
        if(recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cin, &addrlen) < 0)
        {
            ERR_MSG("recvfrom");
            return -1;
        }
        printf("[%s:%d] : %s\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), buf);
    }

    //关闭套接字
    close(sfd);
    return 0;
}

TCP多进程并发服务器

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>

#define ERR_MSG(msg) do{\
    fprintf(stderr, "line:%d: %s %s\n", __LINE__, __FILE__, __func__);\
    perror(msg);\
}while(0)

#define IP "192.168.2.194"  //ifconfig出来的本机IP
#define PORT 6666           //1024~49151,网络字节序

int deal_cli_msg(int newfd, struct sockaddr_in cin);

void handler(int sig)
{
    while(waitpid(-1, NULL, WNOHANG) > 0);
}

int main(int argc, const char *argv[])
{
    //捕获17) SIGCHLD信号
    if(signal(SIGCHLD, handler) ==SIG_ERR)
    {
        ERR_MSG("signal");
        return -1;
    }

    //创建流式套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sfd < 0)
    {
        ERR_MSG("socket");
        return -1;
    }

    //允许端口快速被重用
    int reuse = 1;
    if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("允许端口快速重用成功 __%d__\n", __LINE__);

    //填充服务器的地址信息结构体,给bind函数绑定
    //真实的地址信息结构体根据地址族制定:AF_INET:man 7 ip
    struct sockaddr_in sin;
    sin.sin_family      = AF_INET;          //必须填AF_INET;
    sin.sin_port        = htons(PORT);      //1024~49151,网络字节序
    sin.sin_addr.s_addr = inet_addr(IP);    //ifconfig出来的本机IP

    //绑定服务器的IP和端口---》必须绑定 
    if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("bind success __%d__\n", __LINE__);


    //将套接字设置为被动监听状态 
    if(listen(sfd, 128) < 0)
    {
        ERR_MSG("listen");
        return -1;
    }
    printf("listen success __%d__\n", __LINE__);

    struct sockaddr_in cin;             //存储客户端的地址信息结构体
    socklen_t addrlen = sizeof(cin);
    int newfd = -1;
    pid_t cpid = 0;

    //获取连接成功后的新的套接字文件描述符 
    while(1)
    {
        //父进程只负责交互
        newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
        if(newfd < 0)
        {
            ERR_MSG("accept");
            return -1;
        }
        printf("[%s:%d] 客户端连接成功 newfd=%d __%d__\n",\
                inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, __LINE__);

        //能运行到当前位置,则代表肯定有客户端连接成功;
        //创建一个子进程只负责与客户端进行交互
        cpid = fork();
        if(0 == cpid)
        {
            //子进程运行
            close(sfd);
            deal_cli_msg(newfd, cin);                                                        
            exit(0);        //子进程只负责交互,所以必须要将子进程退出
        }
        else if(cpid > 0)
        {
            close(newfd);
        }
        else
        {
            ERR_MSG("fork");
            return -1;
        }

    }
    close(sfd);
    return 0;
}

int deal_cli_msg(int newfd, struct sockaddr_in cin)
{
    char buf[128] = "";
    ssize_t res = 0;

    while(1)
    {
        bzero(buf, sizeof(buf));
        //接收
        res = recv(newfd, buf, sizeof(buf), 0);
        if(res < 0)
        {
            ERR_MSG("recv");
            return -1;
        }
        else if(0 == res)
        {
            printf("[%s:%d] 客户端下线 newfd=%d __%d__\n",\
                    inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, __LINE__);
            break;
        }

        printf("[%s:%d] newfd=%d :%s __%d__\n",\
                inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, buf, __LINE__);


        //发送
        strcat(buf, "*_*");
        if(send(newfd, buf, sizeof(buf), 0) < 0)
        {
            ERR_MSG("send");
            return -1;
        }
        printf("send success __%d__\n", __LINE__);

    }

    //关闭套接字文件描述符
    close(newfd);

    return 0;
}


TCP多线程并发服务器

#include <myhead.h>


#define ERR_MSG(msg) do{\
    fprintf(stderr, "line:%d: %s %s\n", __LINE__, __FILE__, __func__);\
    perror(msg);\
}while(0)

#define IP "192.168.2.186"  //ifconfig出来的本机IP
#define PORT 6666           //1024~49151,网络字节序
                                                                                                
//需要传入到线程中数据
struct climsg
{
    int newfd;
    struct sockaddr_in cin;
};

void* deal_cli_msg(void* arg);



int main(int argc, const char *argv[])
{
    //创建流式套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sfd < 0)
    {
        ERR_MSG("socket");
        return -1;
    }

    //允许端口快速被重用
    int reuse = 1;
    if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("允许端口快速重用成功 __%d__\n", __LINE__);

    //填充服务器的地址信息结构体,给bind函数绑定
    //真实的地址信息结构体根据地址族制定:AF_INET:man 7 ip
    struct sockaddr_in sin;
    sin.sin_family      = AF_INET;          //必须填AF_INET;
    sin.sin_port        = htons(PORT);      //1024~49151,网络字节序
    sin.sin_addr.s_addr = inet_addr(IP);    //ifconfig出来的本机IP

    //绑定服务器的IP和端口---》必须绑定 
    if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
    {
        ERR_MSG("bind");
        return -1;
    }
    printf("bind success __%d__\n", __LINE__);


    //将套接字设置为被动监听状态 
    if(listen(sfd, 128) < 0)
    {
        ERR_MSG("listen");
        return -1;
    }
    printf("listen success __%d__\n", __LINE__);

    struct sockaddr_in cin;             //存储客户端的地址信息结构体
    socklen_t addrlen = sizeof(cin);
    int newfd = -1;
    pthread_t tid = 0;
    struct climsg info;

    //获取连接成功后的新的套接字文件描述符 
    while(1)
    {
        //主线程负责连接 accept
        //accept阻塞的时候,会先预选一个没有被使用过的文件描述符
        //当解除阻塞的时候,会监测文件描述符是否被使用
        //若没有被使用,则直接返回预选文件描述符
        //若被使用,则需要重新遍历一个没有被用过的文件描述符返回
        newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
        if(newfd < 0)
        {
            ERR_MSG("accept");
            return -1;
        }
        printf("[%s:%d] 客户端连接成功 newfd=%d __%d__\n",\
                inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, __LINE__);

        info.newfd = newfd;
        info.cin = cin;

        //能运行到当前位置,则代表有客户端连接,需要创建一个分支线程负责交互
        if(pthread_create(&tid, NULL, deal_cli_msg, &info) != 0)
        {
            fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
            return -1;
        }

        //分离线程
        pthread_detach(tid);
    }
    close(sfd);
    return 0;
}


//线程处理函数
void* deal_cli_msg(void* arg)       //void* arg = (void*)&info
{
    //newfd cin必须另存,
    //若用全局比那辆,或者指针的方式间接访问,会导致每次连接一个新的客户端,newfd,cin会被覆盖
    int newfd = ((struct climsg*)arg)->newfd;
    struct sockaddr_in cin = ((struct climsg*)arg)->cin;

    char buf[128] = "";
    ssize_t res = 0;
    while(1)
    {
        bzero(buf, sizeof(buf));
        //接收
        res = recv(newfd, buf, sizeof(buf), 0);
        if(res < 0)
        {
            ERR_MSG("recv");
            break;
        }
        else if(0 == res)
        {
            printf("[%s:%d] 客户端下线 newfd=%d __%d__\n",\
                    inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, __LINE__);
            break;
        }

        printf("[%s:%d] newfd=%d :%s __%d__\n",\
                inet_ntoa(cin.sin_addr),ntohs(cin.sin_port), newfd, buf, __LINE__);


        //发送
        strcat(buf, "*_*");
        if(send(newfd, buf, sizeof(buf), 0) < 0)
        {
            ERR_MSG("send");
            break;
        }
        printf("send success __%d__\n", __LINE__);

    }

    //关闭套接字文件描述符
    close(newfd);

    pthread_exit(NULL);
}

tftp下载

#include <myhead.h>

#define ERR_MSG(msg) do{\
	fprintf(stderr, "line:%d %s\t%s", __LINE__, __FILE__, __func__);\
	perror(msg);\
}while(0)

#define IP "192.168.2.82"   //ifconfig出来的本机IP
#define PORT 69            //1024~49151,网络字节序

int main(int argc, const char *argv[])
{
	//1> 创建报式套接字
	int cfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(cfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("create socket success sfd = %d __%d__\n", cfd, __LINE__);

	//绑定客户端自身的地址信息结构体--->非必须绑定
	//若不绑定则操作系统会自动给客户端绑定一个IP和端口

	//2> 填充服务器的地址信息结构体,给sendto函数使用
	//2> sendto函数中,想发给谁,就填谁的地址信息
	struct sockaddr_in sin;
	sin.sin_family      = AF_INET;        
	sin.sin_port        = htons(PORT);    
	sin.sin_addr.s_addr = inet_addr(IP);  

	printf("请输入要下载的文件名>>>");
	char filename[20] = "";
	scanf("%s", filename);
	getchar();

	//组下载请求包
	char buf[516];

	//读写请求大小
	int size = sprintf(buf, "%c%c%s%c%s%c", 0, 1, filename, 0, "octet", 0);

	//发送读写请求
	if(sendto(cfd, buf, size, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
	{
		ERR_MSG("sendto apply");
		return -1;
	}


	socklen_t addrlen = sizeof(sin);
	ssize_t res = 0;
	int fd = -1;
	unsigned short int num = 0;

	//数据接收,下载文件
	while(1)
	{
		//清空
		bzero(buf, sizeof(buf));
		//接收数据包
		res = recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, &addrlen);
		if(res < 0)
		{
			ERR_MSG("recvfrom");
			return -1;
		}

		//判断是错误包还是数据包
		if(buf[1] == 3)          //数据包
		{
			//打开文件,用于存储数据
			if(fd < 0)
			{

				fd = open(filename, O_RDWR|O_CREAT|O_TRUNC, 0664);
				if(fd < 0)
				{
					ERR_MSG("open");
					return -1;
				}
			}

			//判断服务器发送过来的数据包是否重复
			if(htons(num+1) == *(unsigned short*)(buf+2))
			{
				num++;

				//将数据存储到文件中,注意最后一次的数据长度小于512
				if(write(fd, buf+4, res-4) < 0)
				{
					ERR_MSG("write");
					return -1;
				}

				//回复ACK包,由于数据包的前四个字节与ACK包只有操作码不一致
				//所以只需要修改操作码为3即可
				buf[1] = 4;
				if(sendto(cfd, buf, 4, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
				{
					ERR_MSG("sendto ack");
					return -1;
				}

				if(res-2-2 < 512)
				{
					printf("下载完成\n");
					break;
				}
			}
		}

		else if(buf[1] == 5)  //错误包
		{
			printf("download failed: %s\n", buf+4);
			break;
		}
	}
	//关闭套接字
	close(cfd);

	return 0;
}

tftp上传

#include <myhead.h>

#define ERR_MSG(msg) do{\
	fprintf(stderr, "line:%d %s\t%s", __LINE__, __FILE__, __func__);\
	perror(msg);\
}while(0)

#define IP "192.168.2.82"   //ifconfig出来的本机IP
#define PORT 69            //1024~49151,网络字节序

int main(int argc, const char *argv[])
{
	//1> 创建报式套接字
	int sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sfd < 0)
	{
		ERR_MSG("socket");
		return -1;
	}
	printf("create socket success sfd = %d __%d__\n", sfd, __LINE__);

	//绑定客户端自身的地址信息结构体--->非必须绑定
	//若不绑定则操作系统会自动给客户端绑定一个IP和端口

	//2> 填充服务器的地址信息结构体,给sendto函数使用
	//2> sendto函数中,想发给谁,就填谁的地址信息
	struct sockaddr_in sin;
	sin.sin_family      = AF_INET;        
	sin.sin_port        = htons(PORT);    
	sin.sin_addr.s_addr = inet_addr(IP);  

	printf("请输入要上传的文件名>>>");
	char filename[20] = "";
	scanf("%s", filename);
	getchar();

	//打开文件,用于读取数据
	int fd = open(filename, O_RDONLY);
	if(fd < 0)
	{

		if(errno == ENOENT)
		{
			//如果不存在,则提示
			printf("----文件不存在,请检查后重新输入----\n");
			return 0;
		}
		else
		{
			ERR_MSG("open");
			return -1;

		}
	}
	//组下载请求包
	char buf[516];
	//读写请求大小
	int size = sprintf(buf, "%c%c%s%c%s%c", 0, 2, filename, 0, "octet", 0);



	//发送读写请求
	if(sendto(sfd, buf, size, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
	{
		ERR_MSG("sendto apply");
		return -1;
	}
	socklen_t addrlen = sizeof(sin);
	ssize_t res = 0;
	unsigned short int num = 0;

	//数据接收,下载文件
	while(1)
	{
		//接收数据包
		res = recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&sin, &addrlen);
		if(res < 0)
		{
			ERR_MSG("recvfrom");
			return -1;
		}
		//校验ACK

		if(4 == buf[1])
		{
			//判断服务器发送过来的数据包是否重复
			if(htons(num) == *(unsigned short*)(buf+2))
			{
				num++;

				bzero(buf, sizeof(buf));
				*(short*)buf = htons(3);
				*(short*)(buf+2) = htons(num);

				res = read(fd, buf+4, 512);
				if(res < 0)
				{
					ERR_MSG("read");
					break;
				}
				//上传数据包
				if(sendto(sfd, buf, res+4, 0, (struct sockaddr*)&sin, sizeof(sin)) < 0)
				{
					ERR_MSG("sendto");
					break;
				}
				//判断数据是否<512
				if(res < 512)
				{
					printf("文件 %s 上传完毕\n\n", filename);
					break;
				}
			}
		}

	}
	//关闭套接字
	close(sfd);

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值