网络第一课(7)---setsockopt(2)

本文详细介绍了如何在客户端和服务器端自行构建UDP+IP层,通过设置网络选项直接从网络层发送数据的过程,包括socket创建、地址结构体初始化、数据包构建以及使用sendto函数进行数据发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


上一课,我们自己造建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;
}



















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值