gpt4 book ai didi

c - 套接字 sendto() 返回 EINVAL

转载 作者:行者123 更新时间:2023-12-04 09:36:50 25 4
gpt4 key购买 nike

我正在尝试在 C 中发送一个 UDP 数据包。我有以下 sendto():

char* msg = "Hello";

//ret is the return value of getaddrinfo, the address is AF_INET (IPv4)
//and the sock_type is SOCK_DGRAM (UDP)
struct sockaddr_in *ip = (struct sockaddr_in *)ret->ai_addr;

if ((sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)ip,
sizeof(struct sockaddr *))) != -1) {
printf("msg sent successfully");
} else {
printf("Error sending msg: %s\n", strerror(errno));
}

但是,它返回一个错误,指出存在无效参数。查看联机帮助页,我真的无法分辨哪个是无效参数。有什么想法吗?

编辑:这是我所有的代码

#include <stdio.h>  
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>

int main(int argc, const char *argv[])
{
/*
* Help the technically challenged among us who have no idea
* what on God's green Earth they are doing with this thing.
*/
if (argc != 2) {
printf("usage: routetracer <ip address or hostname>\n");
return -1;
}

/*
* hints- parameters for return value of getaddrinfo
* ret- return value of getaddrinfo
*/
struct addrinfo hints, *ret;
int status;
char ipv4[INET_ADDRSTRLEN];
int ttl = 0;
char* msg = "Hello";
int last_hop = 0;

//define what we want from getaddrinfo
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; //IPv4
hints.ai_socktype = SOCK_DGRAM; //UDP packets

//call getaddrinfo to fill ret, w/ error chk
if ((status = getaddrinfo(argv[1], NULL, &hints, &ret)) != 0) {
printf("getaddrinfo: %s\n", gai_strerror(status));
return -1;
}

//extract IPv4 address from ret
struct sockaddr_in* ip = (struct sockaddr_in *)ret->ai_addr;

//convert address from pure numbers to something easier to read
inet_ntop(ret->ai_family, &(ip->sin_addr), ipv4, INET_ADDRSTRLEN);

//kindly inform the user of which hostname they are connecting to
printf("Route for: %s\n", ipv4);

//create a socket
int sock = socket(ret->ai_family, ret->ai_socktype, ret->ai_protocol);

ttl = 1;
if ((setsockopt(sock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl))) != -1) {
printf("TTL set successfully\n");
} else {
printf("Error setting TTL: %s\n", strerror(errno));
}

if ((sendto(sock, msg, strlen(msg), 0, ret->ai_addr,
ret->ai_addrlen)) != -1) {
printf("msg sent successfully");
} else {
printf("Error sending msg: %s\n", strerror(errno));
}
return 0;
}

运行该程序会得到以下输出:

$ ./routetracer www.google.com
Route for: 173.194.46.82
TTL set successfully
Error sending msg: Invalid argument

最佳答案

尝试:

if ((sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)ip, 
sizeof(struct sockaddr_in))) != -1) {

你给它的是指针的大小,而不是结构的大小。而且必须是具体的结构类型,不能是泛型。

关于c - 套接字 sendto() 返回 EINVAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22977839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com