Hi, 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;
char 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