UNIX套接字编程中如何打开和关闭DF标志

时间:2022-04-16 11:00:42
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

int main(int argc, char * argv[])
{
    char* sendbuf = "discovery";
const char *port = "5557";
const char *serverip = "192.168.5.139";
int ret, sd, optval;
struct sockaddr_in sa;


sd = socket(AF_INET, SOCK_DGRAM, 0);


memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(atoi(port));
    sa.sin_addr.s_addr = inet_addr(serverip);


/* Close DF flag */
optval = IP_PMTUDISC_DONT;
if(setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, &optval, sizeof(optval)) == -1){
fprintf(stderr, "setsockopt error\n");
exit(1);
}


ret = sendto(sd, sendbuf, strlen(sendbuf), 0, (struct sockaddr*)&sa, sizeof(sa));
if(-1 == ret)
{
fprintf(stderr, "sendto error\n");
}


/* Open DF flag */
optval = IP_PMTUDISC_DO;
if(setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, &optval, sizeof(optval)) == -1){
fprintf(stderr, "setsockopt error\n");
exit(1);
}


ret = sendto(sd, sendbuf, strlen(sendbuf), 0, (struct sockaddr*)&sa, sizeof(sa));
if(-1 == ret)
{
fprintf(stderr, "sendto error\n");
}


close(sd);
return 0;
}