udp server接收数据并发送数据

需求:

    .编写一个sever接收udp广播,如果有数据接收,就回应自己mac地址;(也可添加条件发送)

    .编写client用于测试;

/*****     server    *********/

/*------------------------------------------------------------------
-   Filename      :   MyBroadcast.c
-   CreateTime    :   2018-04-12    17:00
-   Author        :   tobiu
-   Description   :   Broad cast from server
------------------------------------------------------------------*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 

#include 

#define PORT 7890    //port自己定义
#define MAX  255

unsigned char gwmac[6];

/*************************************
*	@Function : getmac
*	@param	  :
*		mac	:	Storage
*	@Description	:	get ens33 mac,可根据自己网卡名称改变
*************************************/
int getmacx(unsigned char *mac) {
	struct ifreq ifreq;
	int sock;

	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("create socket falied...\r\n");
		return -1;
	}
	strcpy(ifreq.ifr_name, "ens33");

	if (ioctl(sock, SIOCGIFHWADDR, &ifreq) < 0) {
		perror("mac ioctl error:");
		return -1;
	}
	memcpy(mac, ifreq.ifr_hwaddr.sa_data, 6);

	//printf("%02x:%02x:%02x:%02x:%02x:%02x\n ", (unsigned char) ifreq.ifr_hwaddr.sa_data[0], (unsigned char) ifreq.ifr_hwaddr.sa_data[1], (unsigned char) ifreq.ifr_hwaddr.sa_data[2],(unsigned char) ifreq.ifr_hwaddr.sa_data[3], (unsigned char) ifreq.ifr_hwaddr.sa_data[4], (unsigned char) ifreq.ifr_hwaddr.sa_data[5]);

	close(sock);
	return 0;
}


int broadCast(void)
{
	printf("\n\n--- BroadCast will start ---\n\n");

    int sockfd,ret = 0;
    socklen_t len;

	char recv[1024] = {0};
    struct sockaddr_in my_con;
    struct sockaddr_in client;


    sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {   
        perror("socket error!\n");
        return 1;
    }

    my_con.sin_family = AF_INET;
    my_con.sin_port = ntohs(PORT);
    my_con.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY,#define INADDR_ANY ((in_addr_t) 0x00000000)

    /*bind*/
    if (bind(sockfd, (struct sockaddr *)&my_con, sizeof(struct sockaddr)) == -1) {  
    	/* handle exception */  
    	perror("Bind failed!\n");
		return 1; 
	}

    len = sizeof(struct sockaddr_in);
    int size = sizeof(struct sockaddr_in);

	while(1)
	{	
		printf("---- recv data ---\n");
		memset(recv,0,1024);

        ret = recvfrom(sockfd,recv,MAX,0,(struct sockaddr *)&client,(socklen_t*)&size);
        recv[ret] = '\0';

        if(ret < 0)
        {
        	printf("no data\n");
        	continue;
        }

        printf("You got a message (%s) from %s\n",recv,inet_ntoa(client.sin_addr) );

		/* get local mac */
		memset(gwmac, 0, 6);

		if (getmacx(gwmac) == -1) {
			printf("read mac failed-----------\r\n");
			return 1;
		} else {
			printf("read mac successed-----------\r\n");
		}
		int i;
		printf("I will send mac : ");
		for(i=0;i<6;i++) 
		{ 
   			printf("%02x:",gwmac[i]);  
		}
		printf("\n");

		char qbuf[40];
		memset(qbuf,0,40);
		sprintf(qbuf,"%02x:%02x:%02x:%02x:%02x:%02x",gwmac[0],gwmac[1],gwmac[2],gwmac[3],gwmac[4],gwmac[5]);

		printf("qbuf : %s\n",qbuf);
		sendto(sockfd,qbuf,strlen(qbuf),0,(struct sockaddr *)&client,len);		
	}
    close(sockfd);
    return 1;
}

int main(int argc, char const *argv[])
{
	/* code */
	broadCast();
	return 0;
}


/*    client    */

/*------------------------------------------------------------------
-   Filename      :   Udpclient.c
-   CreateTime    :   2018-04-12    17:00
-   Author        :   tobiu
-   Description   :   Broad cast from client
------------------------------------------------------------------*/
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include   
#include  /* netbd.h is needed for struct hostent =) */  
  
#define PORT 7890 /* Open Port on Remote Host */  
#define MAXDATASIZE 100 /* Max number of bytes of data */  
  
/* 
 udp广播通信,执行时需要两个参数如下: 
 ./client 192.168.1.255 
 这样便会对192.168.1这个网段内所有开着./server的主机发送数据 
 */  
int main(int argc, char *argv[])  
{  
    int fd, numbytes; /* files descriptors */  
    char recvbuf[MAXDATASIZE]; /* buf will store received text */  
    char sendbuf[MAXDATASIZE];  
    struct hostent *he; /* structure that will get information about remote host */  
    struct sockaddr_in server,client; /* server's address information */  
    int yes;  
      
    /* this is used because our program will need two argument (IP address and a message) */   
    if (argc !=2) {  
        printf("Usage: %s  \n",argv[0]);  
        exit(1);  
    }  
      
    if ((he=gethostbyname(argv[1]))==NULL){ // calls gethostbyname()  
        printf("gethostbyname() error\n");  
        exit(1);  
    }  
      
    if ((fd=socket(AF_INET, SOCK_DGRAM, 0))==-1){ // calls socket()  
        printf("socket() error\n");  
        exit(1);  
    }  
      
    /* 设置通讯方式对广播,即本程序发送的一个消息,网络上所有主机均可以收到 */  
    yes = 1;  
    setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));  
      
    bzero(&server,sizeof(server));  
    server.sin_family = AF_INET;  
    server.sin_port = htons(PORT); /* htons() is needed again */  
    server.sin_addr = *((struct in_addr *)he->h_addr); /*he->h_addr passes "*he"'s info to "h_addr" */  
      
    socklen_t len;  
    len=sizeof(struct sockaddr_in);  
    while (1) {  
        printf("input message:"); 
        memset(recvbuf,0,MAXDATASIZE);
        fgets(sendbuf,40,stdin);  
        sendto(fd,sendbuf,strlen(sendbuf),0,(struct sockaddr *)&server,len);  
        if ((numbytes=recvfrom(fd,recvbuf,MAXDATASIZE,0,(struct sockaddr *)&server,&len)) == -1){ /* calls recvfrom() */  
            printf("recvfrom() error\n");  
            exit(1);  
        }  
        recvbuf[numbytes]='\0';  
          
        int i;

        printf("I will recv mac :  %s\n",recvbuf);

    }  
      
    close(fd); /* close fd */  
} 

运行结果:

udp server接收数据并发送数据_第1张图片


你可能感兴趣的:(socket)