上一课,我们自己造建udp层,os帮我们构建下层;
下面我们自己构造:udp+ip层,然后直接从网络层,把数据给下一层。
下面我们只给出clinet,服务端与上一课一样。
#include <stdio.h>
#include <netinet/in.h>#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <linux/udp.h>
#include <linux/ip.h>//用系统中的ip头结构体。
//client
int main()
{
int ret=0,fd;
fd = socket(AF_INET,SOCK_RAW,IPPROTO_UDP);
if(fd<0)
{
perror("socket");return 1;
}
struct sockaddr_in recv;
recv.sin_family = AF_INET;
recv.sin_port = htons(9527);
recv.sin_addr.s_addr = inet_addr("192.168.0.43");
int value = 1;//+++++++++这里为1:udp+ip;
为0: udp
int len = 4;//value len = 4字节
ret = setsockopt(fd,IPPROTO_IP,IP_HDRINCL,&value,len);
if(ret < 0)
{
perror("set sock option");return 1;
}
//data
char *p = "cc is gays";
unsigned char buff[1024]={0};
//ip
struct iphdr *ip = (struct iphdr *)buff;
ip->version=4;
ip->ihl = 5;
ip->tos = 0;
ip->tot_len = htons(20+8+10);
ip->id = htons(0);
ip->frag_off=htons(0);
ip->ttl = 64;
ip->protocol = 17;
ip->check = htons(0);
ip->saddr = inet_addr("192.168.0.33");
ip->daddr = inet_addr("192.168.0.33");
//udp
struct udphdr *udp =(struct udphdr *)(buff+20);
udp->source = htons(999);
udp->dest = htons(9527);
udp->len = htons(8+10);//*p字符串长十个字节
udp->check = htons(0);
strcpy(buff+8+20,p);//在ip与udp之上加入我们的数据。
ret= sendto(fd,buff,38,0,(struct sockaddr*)&recv,16);
if(ret < 0)
{
perror("sendto");return 1;
}}
close(fd);
return 0;