简单UDP服务端和客户端

服务端代码:

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

int main(int argc, char *argv[])
{
	int sockfd;
	struct sockaddr_in clt_addr, my_addr;

	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket");
		return -1;
	}

	bzero(&my_addr, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(atoi(argv[2]));
	inet_pton(AF_INET, argv[1], &my_addr.sin_addr);

	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
	{	
		perror("bind");
		return -1;
	}

	/*
	bzero(&clt_addr, sizeof(clt_addr));
	clt_addr.sin_family = AF_INET;
	clt_addr.sin_port = htons(atoi(argv[4]));
	inet_pton(AF_INET, argv[3], &clt_addr.sin_addr);

	//服务端可以调用connect与客户端进行绑定,这样服务端只接收该客户端的数据,recvfrom最后两个参数可设为空
	if (connect(sockfd, (struct sockaddr *)&clt_addr, sizeof(clt_addr)) < 0)
	{
		perror("connect");
		return -1;
	}
	*/
	
	int len = 0;
	char buffer[1500];
	socklen_t addr_len = sizeof(clt_addr);
	
	while ((len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clt_addr, &addr_len)) > 0)
	{
		buffer[len-1] = '\0';
		printf("%s\n", buffer);
	}
	
	close(sockfd);
	return 0;
}

客户端代码:

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

int main(int argc, char *argv[])
{
	int sockfd;
	struct sockaddr_in my_addr, srv_addr;

	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		perror("socket");
		return -1;
	}

	bzero(&srv_addr, sizeof(srv_addr));
	srv_addr.sin_family = AF_INET;
	srv_addr.sin_port = htons(atoi(argv[2]));
	inet_pton(AF_INET, argv[1], &srv_addr.sin_addr);

	/*
	bzero(&my_addr, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(atoi(argv[4]));
	inet_pton(AF_INET, argv[3], &srv_addr.sin_addr);
		
	//如果服务端connect了客户端的ip和port,客户端需要调用bind绑定
	if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
	{
		perror("bind");
		return -1;
	}
	
	//客户端可以调用connect与服务端进行绑定,sendto最后两个参数可设为空
	if (connect(sockfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)))
	{
		perror("connect");
		return -1;
	}
	*/

	int len = 0;
	char *buffer = "hello server!";

	while (1)
	{
		sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
		sleep(5);
	}

	close(sockfd);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值