我正在尝试编写一个使用bind的简单程序。代码在solaris上编译,但是我得到一个bind()失败并出现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;
}
答案 0 :(得分:2)
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)
来电。
答案 1 :(得分:0)