【发布时间】:2023-03-04 11:33:01
【问题描述】:
我的教授指示我们手动制作 UDP 请求并发送它。
到目前为止,我已经构建了 UDP 标头和内容指针.. 问题是 sendto 函数需要数据结构 sockaddr 而我所拥有的只是指示目标 ipv4 的字符串..
那么知道如何将此字符串转换为该结构或是否有不同的发送消息?
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
static void die (const char * format, ...)
{
va_list vargs;
va_start (vargs, format);
vfprintf (stderr, format, vargs);
fprintf (stderr, ".\n");
exit (1);
}
void copy_lower_16_int(void * dest,int value)
{
size_t sz =sizeof(value);
if(sz == 2)
memcpy(dest,&value,2);
else if (sz >2)
{
memcpy(dest,(&value)+sz-2,2);
}
}
int sendTo(void * message,size_t size ,char * destinationIP,unsigned short destinationPort)
{
// Get the target transport protocol number
const char* protocol_name="udp";
struct protoent* protocol=getprotobyname(protocol_name);
if (!protocol) {
die("Protocol %s not found",protocol_name);
}
int protocol_number=protocol->p_proto;
printf(" Protocol %s has number of %d \n",protocol_name,protocol_number);
// Create raw socket for usage with IPv4 & the specified transport protocol (UDP)
int fd=socket(AF_INET,SOCK_RAW,protocol_number);
if (fd==-1) {
die("Failed to create a raw socket, error : %s",strerror(errno));
}
// Construct the UDP datagram
//Calculate total size ( message size + 8 byte for the headers)
size_t total_size = size + 8;
// Calculate the checksum
int checksum = 0x53AF;
void * content = (void*) malloc(total_size);
const int sourcePort = 1524;
copy_lower_16_int(content,sourcePort);
copy_lower_16_int(content+2,destinationPort);
copy_lower_16_int(content+4,total_size);
copy_lower_16_int(content+6,checksum);
memcpy(content+8,message,size);
}
void main(){
printf("Size of int is %d",sizeof(2));
sendTo("Cx",2,"127.0.0.1",5405);
}
【问题讨论】:
-
我不确定,但我认为您需要打开 DGRAM_RAW 套接字,而不是 DGRAM_UDP。 (或类似的东西。)
-
我有完全原始的套接字。
-
通常,您填充一个 sockaddr_in 结构,然后在 sendto() 调用中使用其地址,将其地址转换为 (struct sockaddr *)... 例如sendto(sockfd, buf, len, flags, ( struct sockaddr *)&dest_addr, sizeof(dest_addr));