其他分享
首页 > 其他分享> > UDP通讯示例

UDP通讯示例

作者:互联网

通过UDP实现两个不同进程间的通讯

头文件:proto.h

#ifndef __PROTO_H__
#define __PROTO_H__

#define PORT "5050"   //端口
#define NAMESIZE 11

struct student_st   //自定义传输数据类型
{
  uint8_t name[NAMESIZE];
  uint32_t math;
  uint32_t chinese;
}__attribute__((packed));  //设置结构体字节不对齐

#endif

 

接收方:rcver.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "proto.h"
#define IPSIZE 40

int main()
{
  int lsockfd;
  int ret;
  socklen_t llenth,rlenth;
  struct sockaddr_in ldata,rdata;
  ssize_t lenth;
  struct student_st stu;
  char ipbuff[IPSIZE];

  lsockfd = socket(AF_INET,SOCK_DGRAM,0);  //创建socket文件
  if(lsockfd <0)
  {
    perror("socket()");
    exit(1);
  }

  ldata.sin_family = AF_INET;       //设置服务器监听信息
  ldata.sin_port =htons(atoi(PORT));      //设置端口
  llenth = sizeof(ldata);
  inet_pton(AF_INET,"0.0.0.0",&ldata.sin_addr.s_addr);  //将字符串转为整形数
  ret = bind(lsockfd,(void *)&ldata,llenth);  //监听指定端口
  if(ret <0)
  {
    perror("bind()");
    exit(1);
  }

  while(1)   //循环读取显示
  {
    rlenth = sizeof(rdata);
    lenth = recvfrom(lsockfd,&stu,sizeof(stu),0,(void *)&rdata,&rlenth);   //读取数据
    if(lenth <0)
    {
      perror("recvfrom()");
      exit(1);
    }
    inet_ntop(AF_INET,&rdata.sin_addr.s_addr,ipbuff,IPSIZE);   //将整形数转为点分字符串
    printf("IP:%s PORT:%d\n",ipbuff,ntohs(rdata.sin_port));
    printf("name:%s math:%d chinese:%d\n",stu.name,ntohl(stu.math),ntohl(stu.chinese));  //显示数据
  }

  close(lsockfd);
  exit(0);
}

 

发送方:sender.c

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

int main(int argc,char **argv)
{
  int lsockfd;
  struct student_st stu;
  struct sockaddr_in rsock;
  ssize_t ret;

  if(argc !=2)  //判断传入参数的合法性
  {
    fprintf(stderr,"Usage:%s <ip address>\n",argv[0]);
    exit(1);
  }

  lsockfd = socket(AF_INET,SOCK_DGRAM,0);  //创建socket文件
  if(lsockfd <0)
  {
    perror("lsockfd()");
    exit(1);
  }

  strcpy(stu.name,"Alin");      //设置发送数据
  stu.math =htonl(rand()%100);
  stu.chinese = htonl(rand()%100);
  rsock.sin_family = AF_INET;
  rsock.sin_port = htons(atoi(PORT));    //设置端口
  inet_pton(AF_INET,argv[1],&rsock.sin_addr.s_addr);   //设置发送IP地址
  ret = sendto(lsockfd,&stu,sizeof(stu),0,(void *)&rsock,sizeof(rsock)); 发送信息
  if(ret <0)
  {
    perror("sendto");
    exit(1);
  }

  close(lsockfd);  //关闭文件
  exit(0);
}

 

编译文件:Makefile

all:rcver sender

rcver:rcver.o
  $(CC) $^ -o $@

sender:sender.o
  $(CC) $^ -o $@

clean:
  $(RM) *.o rcver sender

标签:UDP,通讯,示例,stu,exit,lsockfd,include,sin,INET
来源: https://www.cnblogs.com/linux-learn/p/16560501.html