tance

//client.c
/*********************************************************************
 * Filename: bcast_client.c
 * Description:广播客户端代码
 * Author: Eric(wongpz@foxmail.com)
 * Date: 2012-9-14
 ********************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>

#define IP_FOUND "IP_FOUND"
#define IP_FOUND_ACK "IP_FOUND_ACK"
#define IFNAME "eth0"
#define MCAST_PORT 9999

int main(int argc, char*argv[])
{
	int ret = -1;
	int sock = -1;
	int j = -1;
	int so_broadcast = 1;
	struct ifreq *ifr;
	struct ifconf ifc;
	struct sockaddr_in broadcast_addr; //广播地址
	struct sockaddr_in from_addr; //服务端地址
	int from_len = sizeof(from_addr);
	int count = -1;
	fd_set readfd; //读文件描述符集合
	char buffer[1024];
	struct timeval timeout;
	timeout.tv_sec = 2; //超时时间为2秒
	timeout.tv_usec = 0;

	//建立数据报套接字
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
	{
		perror("create socket failed:");
		return -1;
	}

	// 获取所有套接字接口
	ifc.ifc_len = sizeof(buffer);
	ifc.ifc_buf = buffer;
	if (ioctl(sock, SIOCGIFCONF, (char *) &ifc) < 0)
	{
		perror("ioctl-conf:");
		return -1;
	}
	ifr = ifc.ifc_req;
	for (j = ifc.ifc_len / sizeof(struct ifreq); --j >= 0; ifr++)
	{
		if (!strcmp(ifr->ifr_name, "eth0"))
		{
			if (ioctl(sock, SIOCGIFFLAGS, (char *) ifr) < 0)
			{
				perror("ioctl-get flag failed:");
			}
			break;
		}
	}

	//将使用的网络接口名字复制到ifr.ifr_name中,由于不同的网卡接口的广播地址是不一样的,因此指定网卡接口
	//strncpy(ifr.ifr_name, IFNAME, strlen(IFNAME));
	//发送命令,获得网络接口的广播地址
	if (ioctl(sock, SIOCGIFBRDADDR, ifr) == -1)
	{
		perror("ioctl error");
		return -1;
	}
	//将获得的广播地址复制到broadcast_addr
	memcpy(&broadcast_addr, (char *)&ifr->ifr_broadaddr, sizeof(struct sockaddr_in));
	//设置广播端口号
	printf("\nBroadcast-IP: %s\n", inet_ntoa(broadcast_addr.sin_addr));
	broadcast_addr.sin_family = AF_INET;
	broadcast_addr.sin_port = htons(MCAST_PORT);

	//默认的套接字描述符sock是不支持广播,必须设置套接字描述符以支持广播
	ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &so_broadcast,
			sizeof(so_broadcast));

	//发送多次广播,看网络上是否有服务器存在
	int times = 10;
	int i = 0;
	for (i = 0; i < times; i++)
	{
		//一共发送10次广播,每次等待2秒是否有回应
		//广播发送服务器地址请求
		timeout.tv_sec = 2;  //超时时间为2秒
		timeout.tv_usec = 0;
		ret = sendto(sock, IP_FOUND, strlen(IP_FOUND), 0,
				(struct sockaddr*) &broadcast_addr, sizeof(broadcast_addr));
		if (ret < 0)
		{
			continue;
		}

		//文件描述符清0
		FD_ZERO(&readfd);
		//将套接字文件描述符加入到文件描述符集合中
		FD_SET(sock, &readfd);
		//select侦听是否有数据到来
		ret = select(sock + 1, &readfd, NULL, NULL, &timeout);
		switch (ret)
		{
		case -1:
			break;
		case 0:
			perror("select timeout\n");
			break;
		default:
			//接收到数据
			if (FD_ISSET(sock,&readfd))
			{
				count = recvfrom(sock, buffer, 1024, 0,
						(struct sockaddr*) &from_addr, &from_len); //from_addr为服务器端地址
				printf("\trecvmsg is %s\n", buffer);
				if (strstr(buffer, IP_FOUND_ACK))
				{
					printf("\tfound server IP is %s, Port is %d\n",
							inet_ntoa(from_addr.sin_addr),
							htons(from_addr.sin_port));
				}
				return -1;

			}
			break;

		}
	}
	return 0;
}


//server.c
/*********************************************************************
 * Filename: bcast_server.c
 * Description: 广播服务器端代码
 * Author: Eric(wongpz@foxmail.com)
 * Date: 2012-9-14
 ********************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <linux/in.h>
#include <stdlib.h>

#define IP_FOUND "IP_FOUND"
#define IP_FOUND_ACK "IP_FOUND_ACK"
#define PORT 9999

int main(int argc, char*argv[])
{
	int ret = -1;
	int sock;
	struct sockaddr_in server_addr; //服务器端地址
	struct sockaddr_in from_addr; //客户端地址
	int from_len = sizeof(struct sockaddr_in);
	int count = -1;
	fd_set readfd; //读文件描述符集合
	char buffer[1024];
	struct timeval timeout;
	timeout.tv_sec = 2;
	timeout.tv_usec = 0;

	sock = socket(AF_INET, SOCK_DGRAM, 0); //建立数据报套接字
	if (sock < 0)
	{
		perror("sock error");
		return -1;
	}

	memset((void*) &server_addr, 0, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htons(INADDR_ANY );
	server_addr.sin_port = htons(PORT);

	//将地址结构绑定到套接字上
	ret = bind(sock, (struct sockaddr*) &server_addr, sizeof(server_addr));
	if (ret < 0)
	{
		perror("bind error");
		return -1;
	}

	/**
	 * 循环等待客户端
	 */
	while (1)
	{
		timeout.tv_sec = 100;
		timeout.tv_usec = 0;

		//文件描述符集合清0
		FD_ZERO(&readfd);

		//将套接字描述符加入到文件描述符集合
		FD_SET(sock, &readfd);

		//select侦听是否有数据到来
		ret = select(sock + 1, &readfd, NULL, NULL, &timeout); //侦听是否可读
		switch (ret)
		{
		case -1: //发生错误
			perror("select error:");
			break;
		case 0: //超时
			printf("select timeout\n");
			break;
		default:
			if (FD_ISSET(sock,&readfd))
			{
				count = recvfrom(sock, buffer, 1024, 0,
						(struct sockaddr*)&from_addr, &from_len); //接收客户端发送的数据

				//from_addr保存客户端的地址结构
				if (strstr(buffer, IP_FOUND))
				{
					//响应客户端请求
					//打印客户端的IP地址和端口号
					printf("\nClient connection information:\n\t IP: %s, Port: %d\n",
							(char *)inet_ntoa(from_addr.sin_addr),
							ntohs(from_addr.sin_port));

					//将数据发送给客户端
					memcpy(buffer, IP_FOUND_ACK, strlen(IP_FOUND_ACK) + 1);
					count = sendto(sock, buffer, strlen(buffer), 0,
							(struct sockaddr*) &from_addr, from_len);
				}
			}
			break;
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是 HC32L130J8TA 的串口发送和接收例程: 发送代码: ```c #include "hc32l130.h" #define USART_INSTANCE USART1 int main(void) { // 使能外设时钟 Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); Sysctrl_SetPeripheralGate(SysctrlPeripheralM4Clock, TRUE); Sysctrl_SetPeripheralGate(SysctrlPeripheralUart1, TRUE); // 配置 GPIO Gpio_InitIOExt(GPIO_PORT_4, GPIO_PIN_3, GpioDirOut, GpioDrvLevel3); Gpio_SetAfMode(GPIO_PORT_4, GPIO_PIN_2, GpioAf2); // UART1_RX Gpio_SetAfMode(GPIO_PORT_4, GPIO_PIN_3, GpioAf2); // UART1_TX // 配置串口 stc_uart_config_t stcConfig; stcConfig.enRunMode = UartMode1; // 模式1 stcConfig.u32Baudrate = 9600; // 波特率 stcConfig.enDataLength = UartDataLength8; // 数据位8位 stcConfig.enParity = UartParityNone; // 无奇偶校验 stcConfig.enStopBit = UartStopBit1; // 停止位1位 stcConfig.enSamplingMode = UartSingleSampling; // 单次采样 if (Ok != Uart_Init(USART_INSTANCE, &stcConfig)) { while (1) { ; } } while (1) { Uart_SendData(USART_INSTANCE, 'H'); Uart_SendData(USART_INSTANCE, 'e'); Uart_SendData(USART_INSTANCE, 'l'); Uart_SendData(USART_INSTANCE, 'l'); Uart_SendData(USART_INSTANCE, 'o'); Uart_SendData(USART_INSTANCE, '\r'); Uart_SendData(USART_INSTANCE, '\n'); delay_ms(1000); } } ``` 接收代码: ```c #include "hc32l130.h" #define USART_INSTANCE USART1 int main(void) { // 使能外设时钟 Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE); Sysctrl_SetPeripheralGate(SysctrlPeripheralM4Clock, TRUE); Sysctrl_SetPeripheralGate(SysctrlPeripheralUart1, TRUE); // 配置 GPIO Gpio_InitIOExt(GPIO_PORT_4, GPIO_PIN_3, GpioDirOut, GpioDrvLevel3); Gpio_SetAfMode(GPIO_PORT_4, GPIO_PIN_2, GpioAf2); // UART1_RX Gpio_SetAfMode(GPIO_PORT_4, GPIO_PIN_3, GpioAf2); // UART1_TX // 配置串口 stc_uart_config_t stcConfig; stcConfig.enRunMode = UartMode1; // 模式1 stcConfig.u32Baudrate = 9600; // 波特率 stcConfig.enDataLength = UartDataLength8; // 数据位8位 stcConfig.enParity = UartParityNone; // 无奇偶校验 stcConfig.enStopBit = UartStopBit1; // 停止位1位 stcConfig.enSamplingMode = UartSingleSampling; // 单次采样 if (Ok != Uart_Init(USART_INSTANCE, &stcConfig)) { while (1) { ; } } while (1) { uint8_t u8Data; if (Ok == Uart_ReceiveData(USART_INSTANCE, &u8Data, 1, 0xFFFF)) { if (u8Data == 'H') { Uart_SendData(USART_INSTANCE, 'O'); Uart_SendData(USART_INSTANCE, 'K'); Uart_SendData(USART_INSTANCE, '\r'); Uart_SendData(USART_INSTANCE, '\n'); } } } } ``` 注意,以上代码需要配合 HC32L130J8TA 的库文件来编译运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值