I'm having trouble creating a port in Unix. This code keeps returning "Error creating socket (3)", which makes no sense whatsoever, since sockfd must be smaller than 0 to print the error line.
server.c:
int main (int argc, char **argv)
{
int sockfd;
struct sockaddr_in server_sockaddr;
ch开发者_运维技巧ar buff[TRANSFER_BUFFER_LEN];
/* check number of command line arguments */
if (argc < 2)
{
fprintf (stderr, "Usage: %s <port>\n");
exit (EXIT_FAILURE);
}
/* create server socket */
if ((sockfd = createUdpSocket (&sockfd,
&server_sockaddr,
atoi (*(argv + 1)))
) < 0);
{
fprintf (stderr, "Error creating socket (%d).\n", sockfd);
exit (EXIT_FAILURE);
}
...
return 0;
}
socket_utils.h:
int createUdpSocket (int *sockfd, struct sockaddr_in *client_sockaddr, int port)
{
/* create socket */
if ((*sockfd = socket (AF_INET, SOCK_DGRAM, 0)) == -1)
return -1;
memset (client_sockaddr, 0, sizeof (struct sockaddr_in));
client_sockaddr->sin_family = AF_INET;
client_sockaddr->sin_addr.s_addr = htonl (INADDR_ANY);
client_sockaddr->sin_port = htons (port);
/* bind socket */
if (!bind (*sockfd, (struct sockaddr*) &client_sockaddr, sizeof (sockfd)))
{
close (*sockfd);
return -2;
}
return *sockfd;
}
Any ideas? This same function works fine in my client program that doesn't take a port value (instead takes 0).
Cheers,
Rhys
if ((sockfd = createUdpSocket (&sockfd,
&server_sockaddr,
atoi (*(argv + 1)))
) < 0);
Whoops, where'd that semi-colon come from? You've got a stowaway!
Also, this line won't do what you expect:
if (!bind (*sockfd, (struct sockaddr*) &client_sockaddr, sizeof (sockfd)))
The bind()
function returns 0 on success, -1 on failure. Your test is backwards and will error out when bind succeeds rather than fails. It's also got an incorrect &
where you say &client_sockaddr
. And the third argument needs to be the size of the sockaddr_in
struct, not sizeof(sockfd)
. Try:
if (bind (*sockfd, (struct sockaddr*) client_sockaddr, sizeof (struct sockaddr_in)) != 0)
And heck while we're here, your usage printout is missing its argv[0]
argument:
fprintf (stderr, "Usage: %s <port>\n");
Looks like you have too many parentheses which is confusing the code and yourself....Also, here is a useful guide to understanding network programming with sockets courtesy of beej...
精彩评论