发送可变成报文
1.proto.h
#ifndef PROTO_H__
#define PROTO_H__
#define PROTO_H__
#define RCVPORT "1999"
#define NAMESIZE (512-8-8)
struct msg_st
{
uint32_t math;
uint32_t chinese;
uint8_t name[1];
}__attribute__((packed));
#endif
2.客户端发送变成数据 使用格式 ./sdn 127.0.0.1 学生姓名(变长)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include "proto.h"
#define IPSTRSIZE 40
int main(int argc,char * argv[])
{
if(argc<3)
{
fprintf(stderr,"Usage...\n");
exit(1);
}
if(strlen(argv[2])>NAMESIZE)
{
fprintf(stderr,"Name is too long!\n");
exit(1);
}
int sd;
int size;
struct sockaddr_in raddr;
char ipstr[IPSTRSIZE];
sd = socket(AF_INET,SOCK_DGRAM,0);
struct msg_st *sbufp;
socklen_t raddr_len;
if(sd<0)
{
perror("socket()");
exit(1);
}
size = sizeof(struct msg_st) + strlen(argv[2]);
sbufp = malloc(size);
if(sbufp==NULL)
{
perror("malloc()");
}
strcpy(sbufp->name,"xiaoming");
sbufp->math = htonl(rand()%100);
sbufp->chinese = htonl(rand()%100);
raddr.sin_family = AF_INET;
raddr.sin_port = htons(atoi(RCVPORT));
inet_pton(AF_INET,argv[1],&raddr.sin_addr);
if(sendto(sd,sbufp,size,0,(void *)&raddr,sizeof(raddr))<0)
{
perror("sendto()");
exit(1);
}
puts("OK!");
close(sd);
exit(0);
}
3. Server接收数据 (rcver.c)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "proto.h"
#define IPSTRSIZE 40
int main()
{
int sd;
int size;
struct sockaddr_in laddr,raddr;
char ipstr[IPSTRSIZE];
sd = socket(AF_INET,SOCK_DGRAM,0);
struct msg_st *rbufp;
socklen_t raddr_len;
size = sizeof(struct msg_st) + NAMESIZE -1;
rbufp = malloc(size);
if(rbufp == NULL)
{
perror("malloc()");
exit(1);
}
if(sd<0)
{
perror("socket()");
exit(1);
}
laddr.sin_family = AF_INET;
laddr.sin_port = htons(atoi(RCVPORT));
inet_pton(AF_INET,"0.0.0.0",&laddr.sin_addr);
if(bind(sd,(void *)&laddr,sizeof(laddr))<0)
{
perror("bind()");
exit(1);
}
raddr_len = sizeof(raddr);
while(1)
{
recvfrom(sd,rbufp,size,0,(void *)&raddr,&raddr_len);
inet_ntop(AF_INET,&raddr.sin_addr,ipstr,IPSTRSIZE);
printf("----Message from %s:%d--\n",ipstr,ntohs(raddr.sin_port));
printf("NAME = %s\n",rbufp->name);
printf("MATH = %d\n",ntohl(rbufp->math));
printf("CHINESE = %d\n",ntohl(rbufp->chinese));
}
4.效果