gpt4 book ai didi

sockets - 绑定(bind)失败,参数无效错误

转载 作者:行者123 更新时间:2023-12-03 11:53:14 25 4
gpt4 key购买 nike

我正在尝试编写一个使用绑定(bind)的简单程序。代码在 solaris 上编译,但我得到一个 bind() failed with Invalid Argument 错误。

我已经尝试了很多次,但得到了同样的错误,我无法找出错误。

这是代码:

int my_func ()
{
struct sockaddr_storage name;
struct addrinfo hints, *res;
int status;

char hostnamestr[256];
gethostname (hostnamestr, 256);

int iRC;

memset(&hints, 0, sizeof(hints));

hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

if ((status = getaddrinfo(hostnamestr, NULL, &hints, &res) != 0))
{
printf("getaddrinfo: %s\n", gai_strerror(status));
return 1;
}

memcpy(&name, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
monsocket = socket (name.ss_family, SOCK_STREAM, IPPROTO_TCP);
int iLastError = WSAGetLastError ();

if (monsocket == -1)
{
fprintf (stderr, "cannot open socket for monitors [%s]\n", wsaerror (iLastError));
return 1;
}

sockopts(monsocket);
int flags;
flags = fcntl (monsocket, F_GETFL);
iLastError = WSAGetLastError ();

if (flags < 0)
{
fprintf (stderr, "cannot get flags for socket [%s]\n", wsaerror (iLastError));
return 1;
}

iRC = fcntl (monsocket, F_SETFL, flags | O_NONBLOCK);
iLastError = WSAGetLastError ();

if (iRC == -1)
{
fprintf (stderr, "cannot set flags for socket [%s]\n", wsaerror (iLastError));
return 1;
}

int iPort;
if(name.ss_family == AF_INET)
{
((struct sockaddr_in *) &name)->sin_port = htons (8091);
}
else if(name.ss_family == AF_INET6)
{
((struct sockaddr_in6 *) &name)->sin6_port = htons (8091);
}

struct sockaddr_in* ipv = (struct sockaddr_in *) &name;
printf("connecting to addr: %s\n", inet_ntoa(ipv->sin_addr));

iRC = bind (monsocket, (struct sockaddr *) &name, sizeof (name));
iLastError = WSAGetLastError ();

if (iRC == -1)
{
close(monsocket);
monsocket=-1;
fprintf (stderr, "could not bind to port %d\n", iPort);
printf("Error %s",wsaerror (iLastError));
return 1;
}
else
{
fprintf (SCHED_SHOW_MSG, "bound on port %i\n", ntohs (iPort));
}
iRC = listen (monsocket, SOMAXCONN);
iLastError = WSAGetLastError ();

if (iRC == -1)
{
fprintf (stderr, "could not listen to socket [%s]\n", wsaerror (iLastError));
return 1;
}

return 0;
}

最佳答案

bind (monsocket, (struct sockaddr *) &name, sizeof (name))


您的 sizeof(name)产生通用 sockaddr_storage 的大小尺寸。您需要 sockaddr_in 的大小或 sockaddr_in6 .

无论如何,你最好 只需使用 getaddrinfo 中的内容直接 :
monsocket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bind(monsocket, res->ai_addr, res->ai_addrlen);

为了做到这一点,你必须移动你的 freeaddrinfo(res)称呼。

关于sockets - 绑定(bind)失败,参数无效错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18444606/

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